Skip to the workspace
Pebellslearn by building
Lists  ›  Lesson

LPUSH and RPUSH

LPUSH 12 minLPUSH adds items to the head (left) of a list and RPUSH to the tail (right), both creating the list if needed and replying with its new length.

redis / LPUSH and RPUSH

Explore each scene at your own pace.

01 · The rule

The rule

LPUSH and RPUSH

Asha's Wordcraft profile shows her recent activity, newest at the top: "won a round", "earned a badge", "joined a room". The order matters, and new entries arrive constantly. A Redis list is built for exactly this: an ordered sequence you add to at either end.

The rule

L is the left head, R is the right tail; pushes reply with the new length.

A list is an ordered sequence of strings. Picture it laid out left to right: the left end is the head (index 0), the right end is the tail.

127.0.0.1:6379> RPUSH feed:asha joined
(integer) 1
127.0.0.1:6379> RPUSH feed:asha won
(integer) 2
127.0.0.1:6379> LPUSH feed:asha badge
(integer) 3
127.0.0.1:6379> LRANGE feed:asha 0 -1
1) "badge"
2) "joined"
3) "won"
  • LPUSH key item [item ...] adds to the head; RPUSH adds to the tail.
  • Both create the list if the key does not exist, and both reply with the list's new length.
  • LRANGE key 0 -1 shows the whole list from head to tail (you will meet it properly soon).
  • Lists allow duplicates: pushing won twice stores it twice.

Several items in one push. Items are pushed one at a time, in the order you wrote them. With RPUSH that keeps their order. With LPUSH each item lands in front of the previous one, so they come out reversed:

127.0.0.1:6379> LPUSH letters a b c
(integer) 3
127.0.0.1:6379> LRANGE letters 0 -1
1) "c"
2) "b"
3) "a"

LPUSHX and RPUSHX push only if the list already exists, replying 0 otherwise, which avoids creating a stray list by accident.

For an activity feed, push each new event with LPUSH: the newest is always at index 0, ready to display first.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.