Understanding Higher-Order Functions in Python with Practical Examples
This article explains the concept of higher‑order functions in Python, illustrating their flexibility and reusability through ten practical examples—including map, filter, reduce, decorators, partial, and itertools—while providing complete code snippets for each use case.
Higher-order functions are functions that can take other functions as arguments or return them as results, making Python code more flexible, concise, and reusable.
Example 1: Using the map function
The map function applies a given function to each item of an iterable and returns an iterator of the results.
numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x**2, numbers)
print(list(squared)) # 输出:[1, 4, 9, 16, 25]Example 2: The magic of filter
filter selects items from an iterable that satisfy a predicate function.
numbers = [5, 11, 15, 2, 8]
filtered = filter(lambda x: x > 10, numbers)
print(list(filtered)) # 输出:[11, 15]Example 3: Power of reduce
reduce (from functools ) aggregates a sequence into a single value.
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product) # 输出:120Example 4: Functions as parameters
Define a function that accepts another function as an argument.
def apply_function(func, arg):
return func(arg)
def square(x):
return x * x
print(apply_function(square, 5)) # 输出:25Example 5: Elegant decorators
Decorators modify or enhance existing functions.
def log_decorator(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log_decorator
def greet(name):
return f"Hello, {name}"
print(greet("Alice")) # 输出:Calling greet
# Hello, AliceExample 6: sorted with custom key
Sort a list of dictionaries by a specific field.
people = [
{'name': 'Alice', 'age': 25},
{'name': 'Bob', 'age': 22},
{'name': 'Charlie', 'age': 30}
]
sorted_people = sorted(people, key=lambda person: person['age'])
for person in sorted_people:
print(person)Example 7: Using itertools module
itertools.chain concatenates multiple iterables.
import itertools
list1 = [1, 2, 3]
list2 = [4, 5, 6]
chained = itertools.chain(list1, list2)
print(list(chained)) # 输出:[1, 2, 3, 4, 5, 6]Example 8: functools.partial function
partial fixes some arguments of a function, creating a new callable.
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
print(square(5)) # 输出:25
print(cube(5)) # 输出:125Example 9: Versatile zip function
zip combines multiple sequences into tuples.
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 22, 30]
combined = zip(names, ages)
for name, age in combined:
print(f"{name} is {age} years old")Example 10: Logical checks with any and all
any tests if at least one element satisfies a condition; all tests if all elements satisfy it.
numbers = [1, 3, 5, 7, 8]
has_even = any(number % 2 == 0 for number in numbers)
print(has_even) # 输出:True
all_odd = all(number % 2 != 0 for number in numbers)
print(all_odd) # 输出:FalseThese higher-order function examples demonstrate Python's power and flexibility, making code more compact, readable, and maintainable. We hope they help you better understand and apply higher-order functions in your own projects.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.