This chapter explores several powerful and concise functional programming tools in Python, including lambda functions (anonymous functions) and the utility functions map(), filter(), and reduce(). We’ll also revisit variable scope with the global and nonlocal keywords.
1. Lambda Functions (Anonymous Functions)
A lambda function is a small, single-expression function that does not have a formal name (hence, “anonymous”). They are defined using the lambda keyword and are typically used when a function is required for a short time or as an argument to another function.
- Syntax:
lambda arguments: expression - Limitation: A lambda function can have any number of arguments, but it can only have one expression.
# Standard function definition
def add_ten(x):
return x + 10
# Equivalent Lambda function
add_ten_lambda = lambda x: x + 10
print(add_ten_lambda(5))
# Output: 15
2. The map() Function
The map() function applies a given function (often a lambda) to every item in an iterable (like a list) and returns an iterator (which you typically convert to a list).
- Purpose: Transformation. Applying the same change to every element.
- Syntax:
map(function, iterable)
numbers = [1, 2, 3, 4]
# Double every number using a lambda function
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)
# Output: [2, 4, 6, 8]
3. The filter() Function
The filter() function constructs an iterator from elements of an iterable for which a function (the predicate) returns True.
- Purpose: Selection. Keeping only elements that meet a specified condition.
- Syntax:
filter(function, iterable)
scores = [70, 85, 45, 92]
# Keep only scores greater than 80
high_scores = list(filter(lambda x: x > 80, scores))
print(high_scores)
# Output: [85, 92]
4. The reduce() Function
The reduce() function applies a rolling computation to a sequence of values and reduces them to a single cumulative value.
- Requirement:
reduce()is part of thefunctoolsmodule and must be imported. - Purpose: Aggregation. Calculating a single result from an entire sequence.
- Syntax:
reduce(function, iterable)
from functools import reduce
list_of_nums = [1, 2, 3, 4]
# Calculate the product: ((((1 * 2) * 3) * 4) = 24)
product = reduce(lambda x, y: x * y, list_of_nums)
print(product)
# Output: 24
5. Variable Scope Revisited: global and nonlocal
Recall that variables are either local (inside a function) or global (module level). Python protects global variables from accidental modification inside a function.
A. The global Keyword
Used inside a function to explicitly declare that a variable being modified is the global one, not a new local variable.
count = 0 # Global variable
def increment_global():
global count # Declare intent to modify the global 'count'
count += 1
increment_global()
print(count)
# Output: 1 (The global variable was modified)
B. The nonlocal Keyword
Used in nested functions (a function defined inside another function) to refer to a variable in the nearest enclosing scope that is not the global scope.
def outer_function():
message = "Local to outer"
def inner_function():
nonlocal message # Declare intent to modify 'message' in outer_function's scope
message = "Modified by inner"
inner_function()
print(message)
outer_function()
# Output: Modified by inner (nonlocal allowed inner to change outer's variable)
