What is List in Redis?
A List in Redis is an ordered collection of string values, implemented as a double-ended queue (a doubly linked list). Every element is a Redis String, and insertion order is preserved.
Main properties
- Elements are stored in the order they were added.
- Elements can be added and removed from either end, from the front or the back.
- Duplicate values are allowed (it's not a Set).
- It fits queues, stacks, logs, action histories, and temporary buffers.
Example
bash
LPUSH tasks "send the report"
RPUSH tasks "call with the client"
LRANGE tasks 0 -1Result:
javascript
1) "call with the client"
2) "send the report"LPUSH adds to the front, RPUSH adds to the back.
Main commands
| Command | Description |
|---|---|
LPUSH key value [value ...] | add element(s) to the front of the list |
RPUSH key value [value ...] | add element(s) to the back of the list |
LPOP key | remove and return an element from the front |
RPOP key | remove and return an element from the back |
LRANGE key start stop | get a range of elements |
LLEN key | get the list's length |
LINDEX key index | get an element by index |
LREM key count value | remove an element by value |
LTRIM key start stop | trim the list to a range |
A queue example
bash
RPUSH queue "task1"
RPUSH queue "task2"
LPOP queueResult:
javascript
"task1""task2" is left.
This is how a FIFO queue (first in, first out) is implemented.
A stack example
bash
LPUSH stack "item1"
LPUSH stack "item2"
LPOP stackResult:
javascript
"item2"This is how a LIFO stack (last in, first out) works.
Additional capabilities
- The
BLPOPandBRPOPcommands are blocking versions: they wait for an element to appear (handy for asynchronous queues). LPUSHXandRPUSHXadd an element only if the list already exists.LSETlets you change an element by index.
Internal structure
Redis stores lists in two formats:
- Quicklist, the main structure: a combination of a doubly linked list and a ziplist (a compact array).
- Ziplist (deprecated), used for very short lists.
Quicklist picks the optimal storage method: if there are few elements, they're stored compactly in memory, as the list grows, Redis automatically "unpacks" it into a more efficient form.
Uses
- Task queues between services
- Storing a feed of messages or actions
- Implementing undo/redo
- Temporary log buffers
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.