Chapter 04

Functions & Scope (LEGB)

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.

Questions: 20
Format: Predict Output + Multiple Choice
Difficulty: ★★★★☆
Warning — most dangerous chapter so far. The mutable default argument trap (Q1) causes real production bugs. The late-binding closure trap (Q9) has confused Python programmers for years. Read every explanation carefully.
Default Arguments
Q 01Predict the Output
def add_item(item, lst=[]):
    lst.append(item)
    return lst

print(add_item(1))
print(add_item(2))
print(add_item(3))
Output
[1] [1, 2] [1, 2, 3]
Why? This is Python's most famous gotcha. Default argument values are evaluated once when the function is defined, not each time the function is called. The list [] is created once and reused across all calls.

So each call appends to the same list. After 3 calls, the list has all 3 items.

Fix: Use None as the default, then create the list inside the function: def add_item(item, lst=None): lst = [] if lst is None else lst
Q 02Multiple Choice
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Alice"))
print(greet(greeting="Hi", name="Bob"))
Answer: a) "Hello, Alice!", "Hi, Bob!".

Keyword arguments can be passed in any order. greet(greeting="Hi", name="Bob") works even though the parameter order is (name, greeting). Keyword arguments are matched by name, not position.
Q 03Predict the Output
def f(*args, **kwargs):
    print(type(args))
    print(type(kwargs))
    print(args)
    print(kwargs)

f(1, 2, x=3, y=4)
Output
<class 'tuple'> <class 'dict'> (1, 2) {'x': 3, 'y': 4}
Why? *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.
Q 04Multiple Choice
def f(a, b=2, *args):
    print(a, b, args)

f(1, 3, 4, 5)
Answer: a) 1 3 (4, 5).

Positional arguments fill parameters left to right. 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.
LEGB Scope Rules
Q 05Predict the Output
x = "global"

def f():
    print(x)   # reads global x

f()
Output
global
Why? Python looks up names using the LEGB rule: Local → Enclosing → Global → Built-in. Inside 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.
Q 06Predict the Output
x = 10

def f():
    x = 20   # local x — shadows global
    print(x)

f()
print(x)   # global x unchanged
Output
20 10
Why? Assigning 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.
Q 07Multiple Choice
x = 10

def f():
    print(x)   # what happens here?
    x = 20

f()
Answer: c) UnboundLocalError.

Python decides at compile time whether a variable is local or global based on whether it is assigned anywhere in the function. Since 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.

To modify the global x, add global x at the top of the function.
Q 08Predict the Output
x = 10

def f():
    global x
    x = 20

f()
print(x)
Output
20
Why? The 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.
Closures & nonlocal
Q 09Predict the Output
funcs = []
for i in range(3):
    funcs.append(lambda: i)

print(funcs[0]())
print(funcs[1]())
print(funcs[2]())
Output
2 2 2
Why? This is the late-binding closure trap. All three lambdas close over the variable 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.

Fix: Capture the current value by using a default argument: lambda i=i: i. Default arguments are evaluated at definition time, so each lambda captures a different value.
Q 10Predict the Output
def outer():
    x = 10
    def inner():
        nonlocal x
        x = 20
    inner()
    print(x)

outer()
Output
20
Why? 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.
Q 11Multiple Choice
def make_counter():
    count = 0
    def counter():
        nonlocal count
        count += 1
        return count
    return counter

c = make_counter()
print(c(), c(), c())
Answer: b) 1 2 3.

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.
Lambda
Q 12Predict the Output
double = lambda x: x * 2
print(double(5))
print(type(double))
print((lambda x, y: x + y)(3, 4))
Output
10 <class 'function'> 7
Why? 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.
Q 13Multiple Choice
nums = [3, 1, 4, 1, 5, 9]
nums.sort(key=lambda x: -x)
print(nums)
Answer: b) [9, 5, 4, 3, 1, 1].

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.
Function Objects & First-Class
Q 14Predict the Output
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))
Output
42 10 25
Why? In Python, functions are first-class objects — they can be passed as arguments, returned from functions, and stored in data structures. str, abs, and square are all passed by reference to apply(). This is the foundation of higher-order programming.
Q 15Multiple Choice
def f(x):
    return x * 2

g = f
del f
print(g(5))
Answer: b) 10.

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.
Return Values
Q 16Predict the Output
def f():
    pass

def g():
    return

print(f())
print(g())
print(f() is None)
Output
None None True
Why? Any function that doesn't explicitly return a value — or uses bare return — implicitly returns None. Both f() and g() return None. f() is None is True because there's only one None object.
Q 17Predict the Output
def multi_return():
    return 1, 2, 3

result = multi_return()
a, b, c = multi_return()
print(type(result))
print(result)
print(a, b, c)
Output
<class 'tuple'> (1, 2, 3) 1 2 3
Why? 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.
Q 18Multiple Choice
def f(x, /, y, *, z):
    print(x, y, z)

f(1, 2, z=3)    # call A
f(1, y=2, z=3)  # call B
Answer: a) Both work.

Python 3.8+ allows restricting how arguments can be passed. / 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.
Q 19Predict the Output
def f(x=[]):
    x.append(1)
    return x

print(id(f.__defaults__[0]) == id(f()))
print(f())
print(f())
Output
True [1, 1] [1, 1, 1]
Why? 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.
Q 20Multiple Choice
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())
Answer: b) 2.

Closures capture the variable, not the value at the time of closure creation. When 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.
← Chapter 03: Control Flow Chapter 05: Lists & Slicing →