Understanding Python Higher‑Order Functions: map, filter, sorted, reduce and Practical Examples
This article explains what higher‑order functions are in Python, introduces the commonly used map, filter, sorted and reduce functions, demonstrates their usage with clear code examples, and provides exercises for applying these concepts to real‑world data processing tasks.
In Python, a higher‑order function is a function that can take another function as an argument or return a function as a result. Examples include map , filter , sorted and reduce .
1. map – mapping function
def func1(x, y, f): return f(x) + f(y) num = func1(-10, 2, abs) print(num)
The map function applies a given function to each item of one or more iterables and returns an iterator. Example:
lst = [1,2,3,4,5,6,7] lst2 = [10,100,1000,10000] def f1(x, y): return x + y print(list(map(f1, lst, lst2))) print(list(map(lambda x, y: x + y, lst, lst2)))
Convert a list of integers to strings using map :
lst = [1,2,3,4,5] print(list(map(str, lst)))
2. filter – filtering function
print(list(filter(lambda x: x % 2, [1,2,3,4,5,6,7,8,9])))
Filter a list to keep only truthy values after stripping whitespace and removing falsy elements:
lst = ['A','', 'B', None, 'C',' ', 'a', 1, 0] print(list(filter(lambda x: x and str(x).strip(), lst)))
3. sorted – sorting function
Sort a list of strings case‑insensitively:
list1 = ['bob', 'about', 'Zoo', 'Credit'] print(sorted(list1, key=lambda x: x.lower())) print(sorted(list1, key=str.lower))
Sort a dictionary by its values:
d1 = {"a":3, "b":4, "c":2, "d":5} print(dict(sorted(d1.items(), key=lambda x: x[1])))
4. reduce – cumulative reduction
Concatenate a list of numbers into a single integer:
from functools import reduce s = [1,3,5,7,9] print(reduce(lambda x, y: x*10 + y, s))
Calculate the factorial of a number using reduce :
from functools import reduce n = [1,2,3,4,5,6,7] print(reduce(lambda x, y: x*y, n))
5. Practice exercises
Use map to validate usernames against a regular expression, then filter the valid ones:
lst = ["username","a123","Y_78ju","23hu","was23_67hu"] import re def func1(x): if re.findall(r"^[a-zA-Z_][0-9a-zA-Z_]{5,17}$", x): return f"{x}符合规范" else: return f"{x}不符合规范" print(list(map(func1, lst))) print(list(filter(lambda x: re.findall(r"^[a-zA-Z_][0-9a-zA-Z_]{5,17}$", x), lst)))
Find numbers from 1 to 100 divisible by 3:
print(list(filter(lambda x: x % 3 == 0, range(1, 101))))
Compute squares of numbers 1‑10 using map :
print(list(map(lambda x: x*x, range(1, 11))))
Convert a list of digits into a concatenated string using reduce :
print(reduce(lambda x, y: str(x)+str(y), [1,4,5,9]))
Sort a mixed list of positive and negative integers so that positives appear first, then negatives ordered by absolute value:
list1 = [7, -8, 5, 4, 0, -2, -5] print(sorted(list1, key=lambda x: (x <= 0, abs(x)))) print(sorted(list1, key=lambda x: max(list1)-x+1 if x <= 0 else x))
Custom string sorting where the order is: lowercase < uppercase < odd digit < even digit:
s = 'asdf234GDSdsf23' s2 = "".join(sorted(s, key=lambda x: (x.isdigit(), x.isdigit() and int(x) % 2 == 0, x.isupper(), x))) print(s2)
These examples illustrate how higher‑order functions enable concise, functional‑style data processing in Python.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
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.