🐍
Python
Python Tricky Output & Gotchas — "What Will This Print?"
🐍
🐍
Python · Section 2 of 5

Python Tricky Output & Gotchas — "What Will This Print?"

🔒

This section is locked

Unlock every deep-dive, lab, mock interview, and memory map across all 10 topics.

View Plans — from ₹299/month

Already have a plan? Sign in

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

🧠 PYTHON GOTCHAS → MISLED
PYTHON GOTCHASMISLED
─────────────────────────
MMutability trap (default mutable args, list aliasing)
IIdentity vs Equality (is vs → → )
SScope & closures (LEGB, late binding)
LList tricks (shallow copy, slicing, unpacking)
EEvaluation order (short-circuit, ternary, chaining)
DData type surprises (float precision, string interning, tuple)

Q01 — Mutable Default Argument Trap

What will this print?

python — editable
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:

python — editable
# 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:

python — editable
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?