In Redis, the LPUSH
command inserts one or more values into the head of the list at the specified key.
If the key doesn’t exist, it is created as an empty list before performing the push operation. If the key already holds a value that is not a list, an error is returned.
Syntax
The syntax goes like this:
LPUSH key element [element ...]
Where each element
becomes an element in the list. Elements are inserted one after the other to the head of the list, from the leftmost element to the rightmost element.
Example
Here’s a basic example to demonstrate:
LPUSH scores 1 2 3
Result:
(integer) 3
In this case, the LPUSH
operation was successful, and so we got an integer reply with the length of the list after the push operation was performed.
We can now return all values from the list with the LRANGE
command:
LRANGE scores 0 -1
Result:
1) "3" 2) "2" 3) "1"
As mentioned, list elements are inserted one after the other to the head of the list, from the leftmost element to the rightmost element. Therefore our list goes 3, 2, 1 instead of 1, 2, 3. Use RPUSH
to have them inserted in the opposite order.
Here’s what happens when we push more elements to the list:
LPUSH scores 4 5 6
Result:
(integer) 6
This time we get an integer reply of 6
, because that’s how many elements are in the list after the push operation.
And here’s what happens when we use LRANGE
to get the values in the list:
LRANGE scores 0 -1
Result:
1) "6" 2) "5" 3) "4" 4) "3" 5) "2" 6) "1"
When the Key Doesn’t Contain a List
If the key already exists, but it doesn’t contain a list, an error is returned.
Example:
LPUSH username 1 2 3
Result:
(error) WRONGTYPE Operation against a key holding the wrong kind of value
We can use the TYPE
command to find out the type of value that this key is holding:
TYPE username
Result:
string
In this case the key holds a string (which is not a list).