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?"
Practice
set() method do in redis-py?Solution
Step 1: Understand the purpose of
Theset()set()method is used to save data in Redis by associating a value with a key.Step 2: Compare with other methods
get()retrieves data,delete()removes keys, andkeys()lists keys, so they do not store data.Final Answer:
Stores a value with a specified key in Redis -> Option DQuick Check:
set()means store data [OK]
- Confusing set() with get()
- Thinking set() deletes keys
- Assuming set() lists keys
Solution
Step 1: Identify correct method call syntax
In Python, method calls use parentheses with arguments inside, sor.get('name')is correct.Step 2: Check argument format
The key must be a string, so it needs quotes. Options A, B, and D have syntax errors or missing quotes.Final Answer:
r.get('name') -> Option AQuick Check:
Method call with parentheses and string key [OK]
- Omitting quotes around string keys
- Using square brackets instead of parentheses
- Using curly braces instead of parentheses
import redis
r = redis.Redis()
r.set('color', 'blue')
value = r.get('color')
print(value)Solution
Step 1: Understand Redis returns bytes
Theget()method returns the value as bytes, sovalueisb'blue'.Step 2: Print output
Printingvalueshows the bytes literalb'blue', not the decoded string.Final Answer:
b'blue' -> Option BQuick Check:
Redis returns bytes, so output shows b'...' [OK]
- Expecting a plain string without decoding
- Assuming None if key exists
- Thinking code raises error
import redis
r = redis.Redis()
r.set('age', 30)
age = r.get('age')
print(age)Solution
Step 1: Check data storage
Redis-py converts integers to strings automatically, so storing 30 is valid.Step 2: Check retrieval and printing
get()returns bytes, so printingageshows bytes, not a readable string or integer. Decoding is needed.Final Answer:
get() returns bytes, need decoding -> Option AQuick Check:
Decode bytes after get() to read value [OK]
- Thinking set() rejects integers
- Ignoring bytes return type from get()
- Assuming print syntax error
Solution
Step 1: Understand Redis stores strings/bytes
Redis cannot store Python dicts directly; they must be converted to strings.Step 2: Use JSON to serialize and deserialize
Usingjson.dumps()converts dict to string forset(), andjson.loads()converts back afterget().Step 3: Evaluate other options
hmset()is deprecated; direct dict storage fails; storing string without decoding causes errors.Final Answer:
Use set() with json.dumps() and json.loads() after get() -> Option CQuick Check:
Serialize dict to string before storing, deserialize after retrieval [OK]
- Trying to store dict directly
- Using deprecated hmset() method
- Not decoding bytes before json.loads()
Ready to prove it?
Pass the test and this pattern moves unknown
