Redis Lists

By

Learn how to work with Redis lists using LPUSH and RPUSH to add items, LLEN to count them, LPOP and RPOP to remove them, and LRANGE to read a range of items.

~~~

A Redis list is an ordered sequence of strings, stored under a single key. Adding and removing items at either end is fast, even on huge lists, which makes lists a good fit for queues and stacks.

Adding items to a list

LPUSH and RPUSH are the two commands to add items.

LPUSH adds the item at the head of the list (the left), RPUSH at the tail (the right). If the list does not exist yet, the first push creates it:

LPUSH names "Flavio"
(integer) 1

Both commands return the length of the list after the push:

LPUSH names "Syd"
(integer) 2
RPUSH names "Roger"
(integer) 3

You can add duplicate values into a list:

RPUSH names "Flavio"
(integer) 4

A list can hold a big number of items, more than 4 billions.

Reading items

Using LRANGE you can get the items in the list. It takes a start and a stop position, both included. Position 0 is the head, and negative positions count from the end, so -1 means the last item:

LRANGE names 0 -1
1) "Syd"
2) "Flavio"
3) "Roger"
4) "Flavio"

LRANGE names 0 0 returns just the first item. LRANGE names 0 1 returns the first two.

Count how many items are in a list with LLEN:

LLEN names
(integer) 4

Removing items

Get and remove the first item in a list with LPOP. Do the same with the last item using RPOP:

LPOP names
"Syd"

This is where lists shine. RPUSH to add and LPOP to consume gives you a queue: items come out in the order you put them in. LPUSH plus LPOP behaves like a stack instead.

Remove specific values with LREM. It takes a count and a value, so LREM names 1 "Flavio" removes the first occurrence of “Flavio”:

LREM names 1 "Flavio"
(integer) 1

You can limit how long a list is using LTRIM, which keeps the given range and discards everything else. LTRIM names 0 1 cuts the list to just 2 items, the ones at positions 0 and 1.

A pitfall to watch out for

List commands only work on keys that hold lists. If the key already holds a plain string, any push fails:

SET color "blue"
LPUSH color "red"
(error) WRONGTYPE Operation against a key holding the wrong kind of value

Delete the key with DEL color, or pick a different key name.

Also worth knowing: when you pop the last remaining item, Redis deletes the key automatically. An empty list does not exist.

See all the lists commands here.

Tagged: Redis · All topics
~~~

Related posts about redis: