0
0
Redisquery~5 mins

Why lists handle ordered sequences in Redis

Choose your learning style9 modes available
Introduction

Lists keep items in order, just like a line of people waiting. This helps you remember the exact order things were added.

When you want to keep track of tasks in the order they arrive.
When you need to process messages one by one in the order they come.
When you want to store a playlist of songs to play in sequence.
When you want to keep a history of events as they happen.
When you want to add new items to the start or end and keep order.
Syntax
Redis
LPUSH key value [value ...]
RPUSH key value [value ...]
LRANGE key start stop

LPUSH adds items to the start (left) of the list.

RPUSH adds items to the end (right) of the list.

Examples
Adds "task1" then "task2" to the start, so "task2" is first in the list.
Redis
LPUSH tasks "task1"
LPUSH tasks "task2"
LRANGE tasks 0 -1
Adds "song1" then "song2" to the end, so "song1" is first in the list.
Redis
RPUSH songs "song1"
RPUSH songs "song2"
LRANGE songs 0 -1
Returns an empty list if the list does not exist or has no items.
Redis
LRANGE emptylist 0 -1
Sample Program

This adds three fruits to the list in order and then gets all items to show the order is kept.

Redis
RPUSH mylist "apple"
RPUSH mylist "banana"
RPUSH mylist "cherry"
LRANGE mylist 0 -1
OutputSuccess
Important Notes

Lists keep the order of items exactly as added.

Adding to the left or right changes where new items appear.

Lists are good for queues and stacks because order matters.

Summary

Lists store items in the order you add them.

You can add items to the start or end to control order.

Use lists when order of data is important.