How to Create and Manipulate a List in Redis

📣 Sponsor

We have already covered in another tutorial how to create keys in redis with redis-cli. You can find that tutorial here. In this tutorial, we will be looking at how to create lists.

How to create a new list in redis

To create your first list, run the below command:

redis-cli lpush myList "one"

If you are already in redis-cli, you don't need to write it. Simply write lpush myList "one". Above, we create a list with one item called "myList."

How to add to your list in redis

To add a new element to the start of your list, use lpush. For example, to add another item to the start of "myList", run the following:

lpush myList "two"

To add a new element to the end of your list, use rpush.

rpush myList "three"

To add more than one element when using rpush or lpush, separate them with spaces:

lpush myList "four" "five" "six"

Viewing a list with redis

To view a list, run lrange, with your list name and the start and end point you want to retrieve data for. For example, the below will show the first 6 values from our list:

lrange myList 0 5

Similarly, we can start later in the list. The below selects the 3 elements from the 2nd to 5th in our list:

lrange myList 2 4

Removing an item from a list in redis

To remove an item, use lrem to remove counting from the left or rrem from the right. The below removes the first two instances of the list item "one", from the left.

lrem myList 2 "one"

If you simply want to remove the first or last element, use lpop for removing the first, or rpop for removing the last.

lpop myList
Last Updated 1636649236542

More Tips and Tricks for Redis

Subscribe for Weekly Dev Tips

Subscribe to our weekly newsletter, to stay up to date with our latest web development and software engineering posts via email. You can opt out at any time.

Not a valid email