Choose clear Python data shapes
Use lists, dictionaries and immutable values intentionally.
Pick a shape for the operation
A list preserves order and allows duplicates. A set answers membership questions efficiently but does not preserve input order as a contract. A dictionary maps stable keys to values. Choose the shape from the required behavior, not convenience.
Avoid shared defaults
A mutable default argument is created once, then reused across calls. Use None as the default and create a fresh list or dictionary inside the function. This matters most in request handlers, where one user's data must never leak into another call.
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
Preserve order while de-duplicating
For a stream of hashable IDs, a `seen` set plus an output list gives fast membership checks while keeping first-seen order. Use a plain set only if order is irrelevant. If values are unhashable dictionaries, choose a stable key first rather than serializing arbitrary objects and assuming their representation is a business identity.
seen = set()
result = []
for item in items:
if item not in seen:
seen.add(item)
result.append(item)
State mutability in the API
If a function appends to a list supplied by its caller, that caller's list changes too. Either document that mutation or copy the input. An immutable tuple can signal a fixed result, but it does not make nested objects immutable. Test two consecutive calls to a function with optional collection input; this catches shared-default bugs quickly.
Check your understanding
What is wrong with `def add_item(item, items=[])`?
Show explanation
The same list is reused on later calls, so previous items remain. Create a new list per call.
You can read for free. Create an account to save your progress.
Next lesson: Model values without losing meaning →Put this lesson into practice
A practice activity at this level in the same module.
Try: De-duplicate values preserving orderFurther reading
Primary references for this module. Check the current version when behavior or framework guidance may have changed.