In the previous lecture, we saw how Redis lists can be used like queues (FIFO). In this lecture, we will explore how to use Redis lists as a stack, which is last in, first out (LIFO).
Stack Concept Recap
A stack follows the principle:
- Last In, First Out (LIFO)
This means the most recently added item will be removed first.
Redis lists can easily behave like a stack using the left and right push/pop commands.
Clearing the Database
Before starting, clear the database to work from scratch:
FLUSHDB
This ensures no existing keys or lists interfere with our examples.
Creating a List for the Stack
We will create a list and push items into it:
RPUSH users 1 2 3 4 5 6
RPUSH
adds elements to the right-hand side (end) of the list.- You can add items incrementally; it is not necessary to push everything at once.
Check the length of the list:
LLEN users
Output:
(integer) 6
Retrieve the list:
LRANGE users 0 -1
Output:
1) "1" 2) "2" 3) "3" 4) "4" 5) "5" 6) "6"
The last item pushed (6
) is at the end of the list.
Popping Elements as a Stack
To make the list behave like a stack:
- Use
RPOP
(pop from the right-hand side) so that the last inserted element is removed first.
RPOP users # removes 6 RPOP users # removes 5 RPOP users # removes 4
Check the remaining list:
LRANGE users 0 -1
Output:
1) "1" 2) "2" 3) "3"
- Remaining elements are
"1"
,"2"
,"3"
. - The last three elements (
6
,5
,4
) have been removed, following LIFO behavior.
Inserting at the Left Side
You can also insert items at the left-hand side using LPUSH
:
LPUSH users 4
Check the list:
LRANGE users 0 -1
Output:
1) "4" 2) "1" 3) "2" 4) "3"
- Now, the newly inserted element (
4
) is at the start. - Using
LPOP
will remove the element4
first, allowing flexible stack behavior depending on your insertion side.
Removing All Elements
To clear all items in the list:
LPOP users # repeat until nil
- Once all items are removed, the key itself is automatically deleted in Redis.
- Redis does not maintain empty lists, so if a list has no items, the key is removed.
Check keys:
KEYS *
Output:
(empty list)
Key Points About Redis Lists as Stacks
- Stack behavior (LIFO):
- Use
RPUSH
+RPOP
for a classic stack. - Alternatively,
LPUSH
+LPOP
also works.
- Use
- Flexible insertion:
- You can insert at either end (
LPUSH
orRPUSH
) based on your processing logic.
- You can insert at either end (
- Automatic key removal:
- Redis removes the key when the list becomes empty.
- Incremental addition:
- Items can be pushed incrementally; you don’t need to insert everything at once.
- Useful for temporary tasks:
- Ideal for implementing stack-like structures without initializing variables manually.
Redis lists are extremely versatile and can act as queues, stacks, or general ordered collections, depending on which end you push or pop elements from.