Reference Manual • Chapter 5

Functions, Recursion, Lambda & Modules

An authoritative reference manual on function definitions, LEGB scope resolution, returning multiple values, pass-by-object-reference, parameter types, recursion call stack frames, lambda expressions, map/filter/reduce, and modules.

Functions provide modular abstraction and code reuse in Python. This chapter covers function definitions, returning multiple values, LEGB scope rules, object reference passing mechanics, recursion stack frames, lambda expressions, and module organization.

5.1. 1. Function Definitions, Scope Resolution & Pass-by-Object-Reference

Definition: Functions are block statements defined with `def`; Python scope follows the LEGB rule and arguments are passed using Pass-by-Object-Reference (pass-by-assignment).

Core Working Principles:

📦 Layman Analogy: Passing a Storage Locker Key vs Passing a Photo

Mutable Argument (Passing a List): Like handing someone the key to your storage locker—if they modify items inside, your locker contents change!

Immutable Argument (Passing an Integer): Like handing someone a printed photo—if they draw on their copy, your original photo remains untouched!

def calculate_metrics(data_list, multiplier=2, *args, **kwargs):
    # Mutates original list in-place (Pass-by-Object-Reference)
    data_list.append(100)
    
    total = sum(data_list) * multiplier
    average = total / len(data_list)
    
    return total, average  # Returns a Tuple (total, average)

my_numbers = [10, 20, 30]
tot, avg = calculate_metrics(my_numbers, 3)
print(f"Mutated Source List: {my_numbers}")
print(f"Calculated Total: {tot} | Average: {avg}")
5-Marks Exam Scoring Points
  • Python passes arguments by Object Reference.
  • Multiple return values are packed into a single Tuple automatically.
  • *args captures extra positional arguments into a Tuple; **kwargs captures keyword arguments into a Dict.

5.2. 2. Recursion, Lambda Functions & Python Modules

Definition: Recursion involves functions calling themselves; Lambda functions provide anonymous inline expressions; Modules organize code across files.

Core Working Principles:

graph TD
    Call3[factorial 3 Call Stack Push] --> Call2[factorial 2 Call Stack Push]
    Call2 --> Call1[factorial 1: Base Case Met!]
    Call1 -->|Return 1| Unwind2[factorial 2 Unwinds: 2 * 1 = 2]
    Unwind2 -->|Return 2| Unwind3[factorial 3 Unwinds: 3 * 2 = 6]
                    
Architecture Specification 5.1: Recursive Call Stack Push & Unwind Lifecycle
5-Marks Exam Scoring Points
  • Recursive functions must define a valid Base Case to prevent RecursionError stack overflow.
  • Lambda functions evaluate a single inline expression without an explicit return keyword.
  • if __name__ == '__main__': ensures code runs only when executed directly as a script.

✍️ Chapter 5 Reference Exercises & Review Problems

Exercise 5.1: Write a recursive function `fibonacci(n)` that returns the n-th Fibonacci number. Trace the call stack for `fibonacci(4)`.
Step-by-Step Reference Solution:
def fibonacci(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(4))  # Output: 3

- **Call Stack Trace for `fibonacci(4)`:**
1. `fib(4)` calls `fib(3) + fib(2)`.
2. `fib(3)` calls `fib(2) + fib(1)` $\rightarrow$ `(1 + 0) + 1 = 2`.
3. `fib(2)` calls `fib(1) + fib(0)` $\rightarrow$ `1 + 0 = 1`.
4. Result: `2 + 1 = 3`!
Exercise 5.2: Explain what happens when a mutable list is passed to a function vs when an immutable integer is passed.
Step-by-Step Reference Solution:
- **Mutable List:** Function receives a reference pointer to the original memory object. Executing `list.append()` mutates the source list directly in-place.
- **Immutable Integer:** Function receives a reference to the integer object. Performing `x = x + 1` rebinds the local variable parameter to a brand-new integer object; the caller's original integer remains unchanged.