0
0
Redisquery~10 mins

SPOP for random removal in Redis - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - SPOP for random removal
Start with a Redis Set
Call SPOP command
Redis picks a random element
Remove the element from the set
Return the removed element
Set now has one less element
SPOP removes a random element from a Redis set and returns it, reducing the set size by one.
Execution Sample
Redis
SADD fruits apple banana cherry
SPOP fruits
Add three fruits to a set, then remove one random fruit using SPOP.
Execution Table
StepCommandSet Content BeforeActionRemoved ElementSet Content After
1SADD fruits apple banana cherry{}Add elementsN/A{apple, banana, cherry}
2SPOP fruits{apple, banana, cherry}Remove random elementbanana{apple, cherry}
3SPOP fruits{apple, cherry}Remove random elementapple{cherry}
4SPOP fruits{cherry}Remove random elementcherry{}
5SPOP fruits{}Set empty, nothing to remove(nil){}
💡 SPOP stops removing when the set is empty; returns nil if no elements remain.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5
fruits set{}{apple, banana, cherry}{apple, cherry}{cherry}{}{}
removed elementN/AN/Abananaapplecherry(nil)
Key Moments - 2 Insights
Why does SPOP return nil at the last step?
Because the set is empty at step 5 (see execution_table row 5), there is no element to remove, so SPOP returns nil.
Is the element removed by SPOP predictable?
No, SPOP removes a random element each time (see execution_table rows 2-4), so the removed element can vary.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, which element was removed from the set?
Acherry
Bapple
Cbanana
Dnil
💡 Hint
Check the 'Removed Element' column in execution_table row 2.
At which step does the set become empty?
AStep 4
BStep 3
CStep 5
DStep 2
💡 Hint
Look at the 'Set Content After' column to find when the set is {}.
If you call SPOP on an empty set, what will be the result?
AThe last removed element
Bnil
CAn error
DAn empty string
💡 Hint
See execution_table row 5 where SPOP returns nil on empty set.
Concept Snapshot
SPOP key
- Removes and returns a random element from the set stored at key.
- If the set is empty or key does not exist, returns nil.
- Each call reduces the set size by one.
- Useful for random sampling and removal.
Full Transcript
This visual execution trace shows how the Redis SPOP command works for random removal from a set. We start with an empty set named 'fruits'. We add three elements: apple, banana, and cherry. Then, each SPOP command removes one random element from the set and returns it. The set shrinks by one element each time. When the set becomes empty, SPOP returns nil, indicating no elements remain to remove. This helps understand that SPOP picks randomly and reduces the set size until empty.