DEV Community

Divyanshu Shekhar
Divyanshu Shekhar

Posted on • Edited on

Redis List Commands

Lists are present in almost every programming language and play a very important role when it comes to storing information.

Redis an in-memory database also has lists data structure. Its structure is somewhat like linked lists and insertions and deletion can be done by both sides.

Create Redis List

As stated earlier, Redis list insertion can be done from both sides i.e Head and Tail. When the list is seen horizontally the Head comes to the left and the Tail to the right. So the Redis Command to push elements towards Head is LPUSH and towards tail is RPUSH.

LPUSH/RPUSH key value [value ...]
Enter fullscreen mode Exit fullscreen mode

Redis LPUSH

$ 127.0.0.1:6379> lpush number 1 2 3 4 5
  (integer) 5
Redis RPUSH
$ 127.0.0.1:6379> rpush number 1 2 3 4 5
  (integer) 5
Enter fullscreen mode Exit fullscreen mode

Range List Values

Just like in programming languages where we can range over the List values, In the Redis list, we can range over the list items too.

lrange key start end
Enter fullscreen mode Exit fullscreen mode

Ranging the LPUSHed Lists.

lrange LPUSHed List

$ 127.0.0.1:6379> lpush number 1 2 3 4 5
  (integer) 5
$ 127.0.0.1:6379> lrange number 0 5
  1) "5"
  2) "4"
  3) "3"
  4) "2"
  5) "1"
Enter fullscreen mode Exit fullscreen mode

In the Redis LPUSH, the elements are pushed to the head, and thus when looped the output is in reverse order.

Now, Ranging the RPUSHed List.

lrange RPUSHed List

$ 127.0.0.1:6379> rpush number 1 2 3 4 5
  (integer) 5
$ 127.0.0.1:6379> lrange number 0 5
  1) "1"
  2) "2"
  3) "3"
  4) "4"
  5) "5"
Enter fullscreen mode Exit fullscreen mode

You can notice the difference between the two outputs.

In the Redis RPUSH, the elements are pushed to the tail, and thus when looped the output is in the same order as they are pushed.

Read the whole post Redis List Commands from the original Post.

Also Learn how to integrate Redis with Python from the original blog post: Use Redis with Python: The Power of In-Memory Database. More Blogs on Redis.

Top comments (0)