0
0
RedisHow-ToBeginner · 3 min read

How to Use LPOP in Redis: Syntax, Example, and Tips

Use the LPOP command in Redis to remove and return the first element from the left of a list stored at a given key. If the list is empty or the key does not exist, LPOP returns null.
📐

Syntax

The LPOP command syntax is simple:

  • LPOP key: Removes and returns the first element of the list stored at key.
  • If the list is empty or the key does not exist, it returns null.
redis
LPOP key
💻

Example

This example shows how to use LPOP to remove the first item from a list and get its value.

redis
127.0.0.1:6379> RPUSH fruits "apple" "banana" "cherry"
(integer) 3
127.0.0.1:6379> LPOP fruits
"apple"
127.0.0.1:6379> LRANGE fruits 0 -1
1) "banana"
2) "cherry"
Output
"apple" 1) "banana" 2) "cherry"
⚠️

Common Pitfalls

Common mistakes when using LPOP include:

  • Trying to LPOP from a key that does not hold a list, which causes an error.
  • Expecting LPOP to return all elements; it only removes one element at a time.
  • Not handling the null return when the list is empty or key is missing.
redis
127.0.0.1:6379> SET mykey "notalist"
OK
127.0.0.1:6379> LPOP mykey
(error) WRONGTYPE Operation against a key holding the wrong kind of value

-- Correct usage:
127.0.0.1:6379> RPUSH mylist "one" "two"
(integer) 2
127.0.0.1:6379> LPOP mylist
"one"
Output
(error) WRONGTYPE Operation against a key holding the wrong kind of value "one"
📊

Quick Reference

CommandDescription
LPOP keyRemove and return the first element of the list at key
ReturnsThe popped element or null if list is empty or key missing
ErrorWRONGTYPE if key holds a non-list value

Key Takeaways

LPOP removes and returns the first element from a Redis list.
If the list is empty or key does not exist, LPOP returns null.
LPOP only works on keys holding lists; otherwise, it causes an error.
Use LPOP to process list elements in order from left to right.
Always check for null to handle empty or missing lists safely.