Python Tricky Output & Gotchas — "What Will This Print?"
"What will be the output?" — The question that catches even experienced engineers. These are NOT coding questions. These test if you truly UNDERSTAND Python internals.
Memory Map
Q01 — Mutable Default Argument Trap
What will this print?
def add_item(item, lst=[]):
lst.append(item)
return lst
print(add_item("a"))
print(add_item("b"))
print(add_item("c"))
Think about it...
Common Wrong Answer: ['a'], ['b'], ['c']
Most people assume a fresh empty list is created on every call. That is how it works in most other languages.
Actual Output:
# Output:
# ['a']
# ['a', 'b']
# ['a', 'b', 'c']
Why: The default list [] is created ONCE when the function is defined, not each time it is called. Every call shares the SAME list object in memory. Python evaluates default arguments at function definition time, so lst points to the same list across all calls.
The Fix:
def add_item(item, lst=None):
if lst is None: # Create a NEW list each time — None is immutable, safe as default
lst = []
lst.append(item)
return lst
# Output:
# ['a']
# ['b']
# ['c']
Interview Tip: "Never use mutable objects (list, dict, set) as default arguments. Use None and create inside the function. This is Python's most famous gotcha."
What NOT to Say: "I think Python creates a new list each call" — this shows you have not encountered one of the most fundamental Python traps.
Q02 — List Aliasing vs Copy
**What will this print?