Overview of Common Python Built‑in Functions, itertools, and operator Utilities
This article introduces essential Python built‑in functions such as map, filter, reduce, sorted, any, all, zip, enumerate, and utilities from functools, itertools, and operator modules, providing concise explanations and practical code examples for each to help readers master fundamental programming techniques.
map(function, iterable, ...) applies a function to every element of an iterable and returns a new iterator.
numbers = [1, 2, 3, 4] squared = map(lambda x: x**2, numbers) print(list(squared)) # [1, 4, 9, 16]filter(function, iterable) constructs an iterator containing only the elements for which the function returns True.
numbers = [1, 2, 3, 4, 5, 6] even_numbers = filter(lambda x: x % 2 == 0, numbers) print(list(even_numbers)) # [2, 4, 6]reduce(function, iterable[, initializer]) (from functools ) cumulatively applies the function to the items of an iterable, reducing it to a single value.
from functools import reduce product = reduce(lambda x, y: x * y, [1, 2, 3, 4]) print(product) # 24sorted(iterable, key=None, reverse=False) returns a new list containing all items from the iterable in sorted order.
words = ['banana', 'apple', 'cherry'] sorted_words = sorted(words, key=len) print(sorted_words) # ['apple', 'banana', 'cherry']any(iterable) returns True if at least one element of the iterable is true; otherwise False .
numbers = [0, False, None, 3] print(any(numbers)) # Trueall(iterable) returns True only if every element of the iterable is true (or the iterable is empty).
numbers = [1, 2, 3, 4] print(all(numbers)) # Truezip(*iterables) aggregates elements from each iterable into tuples, producing a list of these tuples.
names = ['Alice', 'Bob', 'Charlie'] scores = [85, 90, 78] paired = list(zip(names, scores)) print(paired) # [('Alice', 85), ('Bob', 90), ('Charlie', 78)]enumerate(iterable, start=0) returns an enumerate object yielding pairs of index and value.
for index, value in enumerate(['apple', 'banana', 'cherry']): print(f"Index {index}: {value}")partial(func, *args, **keywords) (from functools ) fixes some portion of a function’s arguments, returning a new callable.
from functools import partial def multiply(a, b): return a * b double = partial(multiply, 2) print(double(5)) # 10wraps(wrapped[, assigned][, updated]) (from functools ) preserves the metadata of the original function when writing decorators.
from functools import wraps def decorator(func): @wraps(func) def wrapper(*args, **kwargs): print("Calling function.") return func(*args, **kwargs) return wrapperfunctools.lru_cache(maxsize=128, typed=False) caches the results of function calls to avoid redundant computation.
from functools import lru_cache @lru_cache(maxsize=1000) def fibonacci(n): if n < 2:
return n return fibonacci(n-1) + fibonacci(n-2) print(fibonacci(10)) # 55itertools.product(*iterables, repeat=1) computes the Cartesian product of input iterables.
from itertools import product colors = ['red', 'green'] sizes = ['S', 'M', 'L'] combinations = list(product(colors, sizes)) print(combinations) # [('red', 'S'), ('red', 'M'), ...]itertools.permutations(iterable, r=None) generates all possible r‑length permutations of the iterable.
from itertools import permutations perms = list(permutations('ABC', 2)) print(perms) # [('A', 'B'), ('A', 'C'), ...]itertools.combinations(iterable, r) yields all r‑length combinations of the iterable.
from itertools import combinations combs = list(combinations('ABC', 2)) print(combs) # [('A', 'B'), ('A', 'C'), ('B', 'C')]operator.itemgetter(*items) creates a callable that fetches the specified item(s) from its operand, useful as a key function.
from operator import itemgetter data = [('apple', 3), ('banana', 2), ('cherry', 1)] sorted_data = sorted(data, key=itemgetter(1)) print(sorted_data) # [('cherry', 1), ('banana', 2), ('apple', 3)]operator.attrgetter(attr) returns a callable that fetches a given attribute from its operand.
from operator import attrgetter class Person: def __init__(self, name, age):
self.name = name
self.age = age people = [Person('Alice', 30), Person('Bob', 25), Person('Charlie', 35)] sorted_people = sorted(people, key=attrgetter('age')) for p in sorted_people:
print(p.name, p.age)functools.cmp_to_key(func) converts an old‑style comparison function to a key function for sorting.
from functools import cmp_to_key def compare(x, y):
return x - y numbers = [5, 2, 9, 1] sorted_numbers = sorted(numbers, key=cmp_to_key(compare)) print(sorted_numbers) # [1, 2, 5, 9]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.