Two standard-library modules turn many hand-written loops into one line. itertools builds and combines iterators: every pair, every permutation, running totals, groups of equal items. functools works on functions themselves: caching results, fixing arguments, and folding a sequence into a single value. Together with a few built-ins like zip, sorted and any, they are the fastest way to write brute-force and search code in Python, which is exactly what most programming challenges call for.
Both build on one idea, the iterator, so that's where we start.
An iterable is anything a for loop can walk over: a list, a string, a dictionary, a file. An iterator is the object that does the walking. It hands out one item at a time and remembers where it is. iter() gets an iterator from an iterable, and next() asks it for the next item, raising StopIteration when there are none left:
1it = iter([10, 20])
2next(it) # Return: 10
3next(itA for loop does exactly this behind the scenes, and stops when it sees StopIteration.
A generator function is the easiest way to write your own iterator. It looks like a normal function, but uses yield instead of return. Each yield hands one value to the caller and pauses the function right there; the next request resumes it from the same spot:
1def countdown(n):
2 while n > 0:
3 yield n
4 n -= Generators are lazy: they only compute a value when it's asked for. That lets them represent sequences that would be too large to store, or even infinite ones, such as every Fibonacci number:
1def fibonacci():
2 a, b = 0, 1
3 while True:
4A loop over fibonacci() would never end on its own; you take what you need and stop, as islice below does.
A generator expression is the lazy version of a list comprehension, written with parentheses instead of square brackets. Passed straight to a function like sum(), it computes the total without ever building a list:
sum(x * x for x in range(1_000_000)) # no million-item list in memory1squares = (x * x for x in range(3))
2listA handful of built-in functions work on any iterable, and they replace a surprising number of loops.
enumerate pairs each item with its index, and zip pairs up items from several iterables, stopping at the shortest. Passing strict=True to zip raises a ValueError if the lengths differ, which catches a mismatched input early.
zip(*rows) is a classic trick: the * passes each row as a separate argument, so zip pairs up the first items of every row, then the second items, and so on. That transposes a grid, turning rows into columns, and it also "unzips" a list of pairs:
1grid = [[1, 2, 3],
2 [4, 5, 6]]map(func, iterable) applies a function to every item, and filter(func, iterable) keeps only the items for which the function returns something truthy. Both are lazy:
1list(map(int, ["1", "2", "3"])) # Return: [1, 2, 3]
2list(filter(A lambda is a small anonymous function written inline: lambda x: x * 2 is a function that takes x and returns x * 2. It's limited to a single expression, and it's mostly used as a quick argument to another function. For anything more involved, a comprehension or a named def is clearer.
sorted() returns a new sorted list from any iterable, and min() and max() find the extremes. All three take a key function, which computes the value to compare for each item, instead of comparing the items themselves:
1words = ["bb", "a", "ccc"]
2sorted(words, key=len) # Return: ['a', 'bb', 'ccc']
3A key function fixes the most common sorting surprise. Strings sort character by character, so IP addresses as strings come out in the wrong order; sorting by a list of their numeric parts gives the right one:
1ips = ["10.0.0.5", "10.0.0.12", "10.0.0.9"]
2sorted(ips)
3# Return: ['10.0.0.12', '10.0.0.5', '10.0.0.9']
4Sorting by a tuple sorts by several fields at once: key=lambda p: (p.score, p.name) orders by score, then by name for equal scores.
any() returns True if at least one item is truthy, and all() returns True if every item is. Both stop as soon as the answer is known. With a generator expression, they replace a loop with a flag:
1nums = [3, 8, 12]
2any(n > 10 for n in nums) # Return: TrueThat last line works because True counts as 1 when summed, as covered in Variables & Types.
itertools is a module of iterator building blocks. Everything in it is lazy, so wrap results in list() to see them. Import the module once and use its functions by name:
import itertools as itFour functions generate every arrangement of some items, which is the heart of any brute-force search:
1list(it.product("ab", repeat=2))
2# Return: [('a', 'a'), ('a', 'b'), ('b', 'a'), ('b', 'b')]
3
4product is every way to pick one item from each input, the same as nested for loops. product(range(10), repeat=4) produces all 10,000 four-digit PINs.permutations is every ordering of r distinct items, where order matters.combinations is every selection of r distinct items, where order doesn't matter.combinations_with_replacement is like combinations, but an item can be picked more than once.These grow fast: there are 3,628,800 permutations of just 10 items. Before brute-forcing, work out how many candidates there are, and whether the search will finish.
count(start, step) counts forever, cycle(iterable) repeats an iterable forever, and repeat(x, n) yields the same value n times, or forever without n. Because they never end, pair them with something that stops: zip, a break, or islice, which takes a slice of any iterator the way slicing works on a list:
1list(it.islice(it.count(10, 5), 4)) # Return: [10, 15, 20, 25]
2list(cycle is what repeats a short key across a long message in XOR encryption.
1list(it.chain([1, 2], [3])) # Return: [1, 2, 3]
2chain joins iterables end to end, and chain.from_iterable flattens a list of lists.pairwise yields each item with the next one, which makes differences between neighbors a one-liner: [b - a for a, b in it.pairwise(nums)].batched (Python 3.12+) splits an iterable into fixed-size chunks.zip_longest is zip that keeps going to the longest input, filling the gaps.accumulate yields running results. By default it's a running total, and it can take any two-argument function, such as max for a running maximum:
1list(it.accumulate([3, 1, 4, 1, 5])) # Return: [3, 4, 8, 9, 14]
2groupby groups consecutive equal items. It yields each key with an iterator over that run, which makes run-length encoding short:
1[(k, len(list(g))) for k, g in it.groupby("aaabccdd")]
2groupby only groups items that are next to each other. To group every equal item in a collection, sort it by the same key first, or use a defaultdict instead.@functools.cache remembers a function's results. The first call with given arguments runs the function and stores the result; every later call with the same arguments returns the stored result immediately. This is called memoization, and it can turn a recursive function that would take years into one that runs instantly:
1from functools import cache
2
3@cache
4def fib(n):
5 return n Without @cache, fib(100) recomputes the same smaller values an astronomical number of times. With it, each value from fib(0) to fib(100) is computed exactly once. fib.cache_info() reports the hits and misses.
Because results are stored in a dictionary keyed by the arguments, every argument must be hashable: pass tuples, not lists. @functools.lru_cache(maxsize=1024) is the same idea with a size limit, discarding the least recently used results when it's full.
RecursionError. sys.setrecursionlimit(10_000) raises the limit for memoized searches that need to go deeper.functools.partial creates a new function with some arguments already filled in. It's handy for passing a configured function to map or as a key:
1from functools import partial
2
3int16 = partial(int, base=16)
4int16("ff") functools.reduce folds an iterable into a single value by applying a two-argument function cumulatively, from left to right:
1from functools import reduce
2
3reduce(lambda a, b: a * b, [1, 2,For common cases there's usually something clearer: sum(), math.prod(), max(), or "".join(). Reach for reduce when the combining step is something custom, such as XORing a list of values together.
@cache is a decorator: a function that takes a function and returns a new one wrapping it. @decorator above a def is shorthand for func = decorator(func). Writing your own is a matter of defining an inner function that does something extra around the call. functools.wraps copies the original function's name and docstring onto the wrapper, so tracebacks and help() still show the real name:
1from functools import wraps
2
3def logged(func):
4 @wraps(func)
The wrapper takes *args and **kwargs so it can pass along any arguments the original function accepts.
Here's a small problem solved three ways: how many ways can three six-sided dice add up to 10?
The direct approach is nested loops, one per die:
1count = 0
2for a in range(1, 7):
3 for b in rangeThat works, but the number of dice is baked into the shape of the code. itertools.product generates the same 216 rolls with the number of dice as a parameter, and counting with sum replaces the counter:
1import itertools as it
2
3sum(sum(roll) == 10 for roll in it.product(range(Both still try every roll, and 6 ** n rolls grows too fast for many dice. A recursive function asks a smaller question instead: the ways to make target with dice dice is the sum, over each face, of the ways to make target - face with one die fewer. With @cache, each (dice, target) pair is computed only once:
1from functools import cache
2
3@cache
4def ways(dice, target):
5That progression is typical of challenge problems. Start with the simplest brute force to get a correct answer on the example, switch to itertools to make it general, and reach for a memoized recursion when the search space explodes.
The same applies to zip, map, filter, file objects and everything in itertools. If you need to loop over the results twice, turn them into a list first.