LPUSH and RPUSH add items to a list in Redis. They help you store and manage ordered data easily.
0
0
LPUSH and RPUSH for insertion in Redis
Introduction
When you want to add a new message to the start of a chat history.
When you need to add tasks to the end of a to-do list.
When you want to keep a list of recent user actions, adding new ones at the front.
When you want to build a queue where new items go to the back.
Syntax
Redis
LPUSH key value [value ...] RPUSH key value [value ...]
LPUSH adds values to the start (left) of the list.
RPUSH adds values to the end (right) of the list.
Examples
Adds "apple" to the start of the list named mylist.
Redis
LPUSH mylist "apple"Adds "banana" to the end of the list named mylist.
Redis
RPUSH mylist "banana"Adds "cherry" and "date" to the start of mylist, with "date" becoming the first element.
Redis
LPUSH mylist "cherry" "date"
Adds "elderberry" and "fig" to the end of mylist, in that order.
Redis
RPUSH mylist "elderberry" "fig"
Sample Program
This example clears the list 'fruits', then adds items using LPUSH and RPUSH. Finally, it shows the full list.
Redis
DEL fruits LPUSH fruits "apple" RPUSH fruits "banana" LPUSH fruits "cherry" "date" RPUSH fruits "elderberry" "fig" LRANGE fruits 0 -1
OutputSuccess
Important Notes
LPUSH inserts items in the order they are given, so the last value ends up at the front.
RPUSH inserts items in the order they are given, so the first value ends up just after the existing last element.
If the list does not exist, Redis creates it automatically when you use LPUSH or RPUSH.
Summary
LPUSH adds items to the start (left) of a Redis list.
RPUSH adds items to the end (right) of a Redis list.
Both commands create the list if it does not exist.