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;RPUSHadds 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 -1shows the whole list from head to tail (you will meet it properly soon).- Lists allow duplicates: pushing
wontwice 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.
The shortcut
Build the list on paper, one item at a time. For RPUSH, write each item at the right end; for LPUSH, write each at the left end. Never try to place a multi-item push in one jump.
LPUSH 1
Empty list, so it becomes
1.
Drills
Answer fast — trust the rule.
nums does not exist. What is the list after RPUSH nums 1 2 3?
feed:ravi holds 2 items. What does LPUSH feed:ravi won lost reply?
colors does not exist. What is the list after LPUSH colors red green blue?
feed:zoe does not exist. What does RPUSHX feed:zoe joined reply?
Remember
- L is the left head, R is the right tail; pushes reply with the new length.
- Build the list one item at a time: multi-item LPUSH comes out reversed.
- A feed uses LPUSH so the newest item is always at index 0.
