How to Create and Manipulate a List in Redis


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:

shell Copy
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:

shell Copy
lpush myList "two"

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

shell Copy
rpush myList "three"

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

shell Copy
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:

shell Copy
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:

shell Copy
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.

shell Copy
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.

shell Copy
lpop myList
Last Updated Thursday, 11 November 2021

Subscribe to Newsletter

Subscribe 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