The mutable default argument is Python's most famous bug. Late-binding closures catch everyone. LEGB scope rules are subtle. This chapter will find your gaps.
def add_item(item, lst=[]): lst.append(item) return lst print(add_item(1)) print(add_item(2)) print(add_item(3))
[] is created once and reused across all calls.None as the default, then create the list inside the function:
def add_item(item, lst=None): lst = [] if lst is None else lst
def greet(name, greeting="Hello"): return f"{greeting}, {name}!" print(greet("Alice")) print(greet(greeting="Hi", name="Bob"))
greet(greeting="Hi", name="Bob") works even though the parameter order is (name, greeting). Keyword arguments are matched by name, not position.
def f(*args, **kwargs): print(type(args)) print(type(kwargs)) print(args) print(kwargs) f(1, 2, x=3, y=4)
*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dict. The names args and kwargs are just convention — you could write *a, **kw. Order of parameters must always be: positional, *args, keyword-only, **kwargs.
def f(a, b=2, *args): print(a, b, args) f(1, 3, 4, 5)
a=1, b=3 (overrides the default 2), and the remaining 4, 5 go into *args as a tuple. The default value for b is unused because a positional argument was provided.
x = "global" def f(): print(x) # reads global x f()
f(), there is no local x, so Python looks in the global scope and finds "global". Reading a global variable from a function is fine without any special keyword.
x = 10 def f(): x = 20 # local x — shadows global print(x) f() print(x) # global x unchanged
x = 20 inside the function creates a new local variable x that shadows the global x. The global is untouched. When f() exits, the local disappears.
x = 10 def f(): print(x) # what happens here? x = 20 f()
x = 20 exists in f(), Python marks x as local throughout the entire function. The print(x) at the top tries to read a local variable before it's assigned → UnboundLocalError.x, add global x at the top of the function.
x = 10 def f(): global x x = 20 f() print(x)
global x declaration tells Python to use the global x rather than creating a local one. After f() runs, the global x is modified to 20. Using global is generally discouraged — it makes code hard to reason about. Prefer returning values from functions.
funcs = [] for i in range(3): funcs.append(lambda: i) print(funcs[0]()) print(funcs[1]()) print(funcs[2]())
i, not the value at creation time. By the time any lambda is called, the loop has finished and i == 2. So all three return 2.lambda i=i: i. Default arguments are evaluated at definition time, so each lambda captures a different value.
def outer(): x = 10 def inner(): nonlocal x x = 20 inner() print(x) outer()
nonlocal x tells the inner function to use the x from the enclosing (outer) function's scope — the "E" in LEGB. Without nonlocal, x = 20 inside inner() would create a new local variable. With nonlocal, it modifies the outer function's x.
def make_counter(): count = 0 def counter(): nonlocal count count += 1 return count return counter c = make_counter() print(c(), c(), c())
make_counter() returns a closure that remembers its own count variable across calls. Each call to c() increments and returns the same count. This is the classic closure use case — a stateful function without a class. The nonlocal keyword is what makes the increment persist.
double = lambda x: x * 2 print(double(5)) print(type(double)) print((lambda x, y: x + y)(3, 4))
lambda creates an anonymous function. It's a regular function object — same type as functions defined with def. The third line is a lambda defined and immediately called (IIFE pattern). Lambdas can only have one expression — no statements, no assignments.
nums = [3, 1, 4, 1, 5, 9] nums.sort(key=lambda x: -x) print(nums)
sort(key=fn) sorts by the value returned by the key function. lambda x: -x negates each value, so sorting in ascending order of -x gives descending order of x. Equivalent to nums.sort(reverse=True) but shows how key functions work.
def apply(func, value): return func(value) print(apply(str, 42)) print(apply(abs, -10)) def square(x): return x ** 2 print(apply(square, 5))
str, abs, and square are all passed by reference to apply(). This is the foundation of higher-order programming.
def f(x): return x * 2 g = f del f print(g(5))
g = f makes g point to the same function object as f. del f removes the name f from the namespace, but the underlying function object still exists because g still references it. The function is only garbage-collected when all references are gone.
def f(): pass def g(): return print(f()) print(g()) print(f() is None)
return — implicitly returns None. Both f() and g() return None. f() is None is True because there's only one None object.
def multi_return(): return 1, 2, 3 result = multi_return() a, b, c = multi_return() print(type(result)) print(result) print(a, b, c)
return 1, 2, 3 actually returns a tuple. The comma creates the tuple — parentheses are optional. You can then unpack it directly: a, b, c = multi_return(). Python functions don't truly return multiple values — they return one tuple that gets unpacked.
def f(x, /, y, *, z): print(x, y, z) f(1, 2, z=3) # call A f(1, y=2, z=3) # call B
/ means parameters before it are positional-only (cannot use keyword). * means parameters after it are keyword-only (must use keyword). x is positional-only, y is either, z is keyword-only. Both calls satisfy these rules.
def f(x=[]): x.append(1) return x print(id(f.__defaults__[0]) == id(f())) print(f()) print(f())
f.__defaults__ stores the default argument objects. The first print confirms the default list object is the exact same object returned by f(). By the time we print f() again, the default list already has one item (from the id check call), so it shows [1, 1]. Each subsequent call adds another 1.
def f(): x = 1 def g(): return x # reads from enclosing scope x = 2 # changed AFTER g is defined return g result = f() print(result())
g() is called, it looks up x in the enclosing scope at call time. By then, x = 2 has already executed. This is the same principle as the late-binding lambda trap in Q09 — closures always see the current value of captured variables.