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:
- LEGB Scope Resolution Hierarchy: Searches variables in order: **L**ocal $\rightarrow$ **E**nclosing (nested functions) $\rightarrow$ **G**lobal $\rightarrow$ **B**uilt-in.
- Returning Multiple Values: Python packs multiple comma-separated return values into a single Tuple automatically.
- Functions vs Methods: Functions stand independently (`len(x)`); Methods belong to an object class (`list.append()`).
- Pass-by-Object-Reference Mechanics:
- • Mutable Arguments (Lists, Dicts): Modifications inside function mutate the original object in-place!
- • Immutable Arguments (Ints, Strings, Tuples): Reassignment binds local variable to a new memory reference; original caller object remains untouched.
- Parameter Taxonomy: Positional, Keyword (`key=val`), Default (`param=val` evaluated once at definition time), Variable-length positional (`*args` tuple), Variable-length keyword (`**kwargs` dict).
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:
- Recursive Call Stack Mechanics: Require a Base Case (halts recursion) and a Recursive Step (approaches base case). Each invocation pushes a new frame onto the execution call stack. Exceeding `sys.getrecursionlimit()` raises `RecursionError`.
- Lambda Functions & Functional Tools: One-line anonymous functions (`lambda x, y: x + y`). Frequently combined with `map()`, `filter()`, and `functools.reduce()`.
- Python Modules: Structuring code into `.py` files, importing via `import module` or `from module import func`, searching `sys.path`, and guarding script execution using `if __name__ == '__main__':`.
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]
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
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`!
- **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.