Redis with Python (redis-py) - Time & Space Complexity
When using Redis commands through Python, it's important to understand how the time to run commands changes as the data grows.
We want to know how the number of operations grows when we run common Redis commands with redis-py.
Analyze the time complexity of the following Python code using redis-py.
import redis
r = redis.Redis()
# Add 1000 items to a Redis list
for i in range(1000):
r.lpush('mylist', i)
# Retrieve all items
items = r.lrange('mylist', 0, -1)
This code pushes 1000 items to a Redis list and then retrieves all items from that list.
Look for repeated actions that affect time.
- Primary operation: The loop calls
lpush1000 times to add items. - How many times: 1000 times for adding, then one
lrangeto get all items.
As the number of items increases, the time to add and retrieve grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | ~10 calls to lpush, 1 call to lrange returning 10 items |
| 100 | ~100 calls to lpush, 1 call to lrange returning 100 items |
| 1000 | ~1000 calls to lpush, 1 call to lrange returning 1000 items |
Pattern observation: The number of lpush calls grows linearly with input size, and retrieving all items also grows linearly with the list size.
Time Complexity: O(n)
This means the time to add and retrieve items grows in direct proportion to the number of items.
[X] Wrong: "Adding items with lpush is always constant time regardless of list size."
[OK] Correct: While lpush is generally fast and operates in O(1) time per call, calling it many times adds up linearly, so total time grows with the number of items added.
Understanding how Redis commands scale with data size helps you explain your choices clearly and shows you know how to handle real data growth.
"What if we used rpush instead of lpush? How would the time complexity change?"