Fundamentals 7 min read

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.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Understanding Higher-Order Functions in Python with Practical Examples

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)  # 输出:120

Example 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))  # 输出:25

Example 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, Alice

Example 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))    # 输出:125

Example 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)   # 输出:False

These 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonMAPreducefilter
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.