Skip to the workspace
Pebellslearn by building
Lists  ›  Lesson

LPOP and RPOP

LPOP 12 minLPOP removes and returns the head item and RPOP the tail item, so pushing and popping at opposite ends gives a queue and at the same end gives a stack.

redis / LPOP and RPOP

Explore each scene at your own pace.

01 · The rule

The rule

LPOP and RPOP

Players who press "Find a match" in Wordcraft wait in line. The matchmaker should always pair the player who has waited longest, and each player must be taken exactly once. Pushing at one end of a list and popping at the other gives you that line for free.

The rule

Opposite ends make a queue; the same end makes a stack.

LPOP key removes the item at the head and returns it; RPOP key does the same at the tail. Popping a missing or empty list replies (nil), and when the last item is popped the key is deleted.

127.0.0.1:6379> RPUSH queue:match asha ravi meera
(integer) 3
127.0.0.1:6379> LPOP queue:match
"asha"
127.0.0.1:6379> LPOP queue:match
"ravi"
127.0.0.1:6379> RPUSH queue:match tom
(integer) 2
127.0.0.1:6379> LPOP queue:match
"meera"
127.0.0.1:6379> LPOP queue:match
"tom"
127.0.0.1:6379> LPOP queue:match
(nil)

Queue (first in, first out). Push at one end and pop at the other: RPUSH + LPOP (or LPUSH + RPOP). The oldest item leaves first. This is the fair match queue above.

Stack (last in, first out). Push and pop at the same end: LPUSH + LPOP. The newest item leaves first, like an undo history.

Popping several. Since Redis 6.2, LPOP key count removes up to count items and returns them as a list: LPOP queue:match 2 takes two players at once.

Waiting instead of polling. A matchmaker that calls LPOP in a loop wastes effort while the queue is empty. BLPOP queue:match 5 blocks until an item arrives or 5 seconds pass, then replies with the key name and the item, or (nil) on timeout. BRPOP is the tail version.

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