0
0
RedisHow-ToBeginner · 3 min read

How to Use LPUSH in Redis: Syntax and Examples

Use the LPUSH command in Redis to add one or more elements to the beginning of a list stored at a key. The syntax is LPUSH key element [element ...], which inserts elements from left to right. If the list does not exist, Redis creates it automatically.
📐

Syntax

The LPUSH command adds one or more elements to the start (left) of a list stored at a given key.

  • key: The name of the list.
  • element: One or more values to add to the list.

If the list does not exist, Redis creates a new list with the given elements.

redis
LPUSH key element1 element2 ...
💻

Example

This example shows how to add elements to a list named fruits using LPUSH. It adds 'apple' and 'banana' to the start of the list.

redis
127.0.0.1:6379> LPUSH fruits apple
(integer) 1
127.0.0.1:6379> LPUSH fruits banana
(integer) 2
127.0.0.1:6379> LRANGE fruits 0 -1
1) "banana"
2) "apple"
Output
1 2 1) "banana" 2) "apple"
⚠️

Common Pitfalls

Common mistakes when using LPUSH include:

  • Using LPUSH on a key holding a non-list type causes an error.
  • Expecting elements to be added to the end of the list instead of the start.
  • Not realizing that multiple elements are added from left to right, so the last element listed becomes the first in the list.
redis
127.0.0.1:6379> SET mykey "value"
OK
127.0.0.1:6379> LPUSH mykey element
(error) WRONGTYPE Operation against a key holding the wrong kind of value

-- Correct usage --
127.0.0.1:6379> LPUSH mylist element1 element2
(integer) 2
127.0.0.1:6379> LRANGE mylist 0 -1
1) "element2"
2) "element1"
Output
(error) WRONGTYPE Operation against a key holding the wrong kind of value 2 1) "element2" 2) "element1"
📊

Quick Reference

CommandDescriptionReturn Value
LPUSH key elementAdd element(s) to the start of the listNew length of the list
LRANGE key 0 -1Get all elements of the listList of elements
RPUSH key elementAdd element(s) to the end of the listNew length of the list

Key Takeaways

LPUSH adds elements to the start (left) of a Redis list.
If the list does not exist, LPUSH creates it automatically.
Multiple elements are added in the order they appear, left to right.
Using LPUSH on a non-list key causes an error.
Use LRANGE to view the list contents after pushing.