Skip to content

Step 1 of 3 · Reading · ~2 min

Pop & Length

Lists

Popping and measuring lists

With LPUSH/RPUSH in place, this lesson adds the other half of the queue/stack interface: removing elements and reporting size.

LPOP and RPOP

These remove from the head and tail respectively, using your deque's O(1) operations:

python

RPOP is identical but calls dq.pop() instead. The wire reply for a found element is a normal bulk string ($<len>\r\n<value>\r\n); for a missing key or an empty list, Redis replies with the null bulk string: $-1\r\n — not an empty string $0\r\n\r\n. Those are different values to a real Redis client (nil vs ""), so don't conflate them.

The auto-delete rule

This is the detail most implementations miss: once the last element is popped, the key itself must cease to exist — not just become an empty list. That matters for three reasons:

  1. EXISTS mylist must now return 0.
  2. TYPE mylist must now return +none\r\n, not +list\r\n.
  3. A later LPUSH on the same key must be free to create a fresh list rather than appending to a lingering empty one (behaviorally identical here, but conceptually — and for memory accounting in real Redis — the key is gone).

Encapsulate this as a small helper you call after every pop:

python

LLEN

Straightforward, but still needs the "missing key = 0" convention that's universal across Redis collection types:

python

Reply as a RESP integer: :0\r\n for a missing key, :3\r\n for three elements. Don't special-case the missing-key path into an error — LLEN on a nonexistent key is a perfectly normal query in real applications (e.g. checking whether a queue has any pending jobs) and must succeed with 0.

Edge case checklist

  • LPOP/RPOP on a key that doesn't exist → $-1\r\n, no error.
  • LPOP/RPOP on a key holding a different type → WRONGTYPE.
  • Repeated pops until empty must delete the key exactly once, not error on the emptying pop.
  • LLEN never errors on a missing key.

Getting these boundary behaviors exactly right is what separates a toy list implementation from one that survives the test suite's edge cases.

Up nextLRANGE — Querying List RangesLists

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…