How to Use RPOP in Redis: Syntax, Example, and Tips
Use the
RPOP command in Redis to remove and return the last element from a list stored at a given key. If the list is empty or the key does not exist, RPOP returns null. This command is useful for treating a Redis list like a stack or queue from the right end.Syntax
The basic syntax of the RPOP command is:
RPOP key: Removes and returns the last element of the list stored atkey.- If the list is empty or the key does not exist, it returns
null.
redis
RPOP key
Example
This example shows how to use RPOP to remove the last element from a Redis list named fruits.
redis
LPUSH fruits apple banana cherry RPOP fruits
Output
"cherry"
Common Pitfalls
Common mistakes when using RPOP include:
- Trying to
RPOPfrom a key that does not hold a list, which causes an error. - Expecting
RPOPto return multiple elements at once (it only returns one element). - Not handling the
nullresponse when the list is empty or the key is missing.
redis
RPOP mykey # Wrong: expecting multiple elements RPOP mylist 3 # This is invalid syntax # Right: use RPOP multiple times or use RPOPLPUSH for atomic operations
Quick Reference
| Command | Description |
|---|---|
| RPOP key | Removes and returns the last element of the list at key |
| Returns | The popped element as a string, or null if list is empty or key missing |
| Error | If key holds a non-list value, returns an error |
Key Takeaways
RPOP removes and returns the last element from a Redis list.
If the list is empty or key does not exist, RPOP returns null.
RPOP only removes one element per call; use loops or other commands for multiple elements.
Avoid using RPOP on keys that are not lists to prevent errors.
Use RPOP to implement stack or queue behavior from the right end of a list.