Table of Contents
IronForgeCyber
Courses
Resources
Blog
Log In


IronForgeCyber

AboutPrivacyTerms

© 2026 IronForgeCyber. All rights reserved.

  1. courses
  2. python
  3. functools-itertools
12 min read

Functools & Itertools

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.

Iterators and Generators

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:

python
1it = iter([10, 20])
2next(it)      # Return: 10
3next(it

A for loop does exactly this behind the scenes, and stops when it sees StopIteration.

Generators

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:

python
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:

python
1def fibonacci():
2    a, b = 0, 1
3    while True:
4

A 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:

python
sum(x * x for x in range(1_000_000))     # no million-item list in memory
Iterators run out
An iterator can only be walked once. After it's exhausted, it yields nothing, and it doesn't raise an error to tell you:
python
1squares = (x * x for x in range(3))
2list

Built-in Helpers

A handful of built-in functions work on any iterable, and they replace a surprising number of loops.

zip and enumerate

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:

python
1grid = [[1, 2, 3],
2        [4, 5, 6]]

map, filter and lambda

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:

python
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, min and max

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:

python
1words = ["bb", "a", "ccc"]
2sorted(words, key=len)              # Return: ['a', 'bb', 'ccc']
3

A 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:

python
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']
4

Sorting 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, all and sum

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:

python
1nums = [3, 8, 12]
2any(n > 10 for n in nums)      # Return: True

That last line works because True counts as 1 when summed, as covered in Variables & Types.

itertools

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:

python
import itertools as it

Combinatorics

Four functions generate every arrangement of some items, which is the heart of any brute-force search:

python
1list(it.product("ab", repeat=2))
2# Return: [('a', 'a'), ('a', 'b'), ('b', 'a'), ('b', 'b')]
3
4
  • product 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.

Infinite Iterators

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:

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

Combining and Grouping

python
1list(it.chain([1, 2], [3]))                    # Return: [1, 2, 3]
2
  • chain 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:

python
1list(it.accumulate([3, 1, 4, 1, 5]))        # Return: [3, 4, 8, 9, 14]
2

groupby groups consecutive equal items. It yields each key with an iterator over that run, which makes run-length encoding short:

python
1[(k, len(list(g))) for k, g in it.groupby("aaabccdd")]
2
Warning
groupby 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

@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:

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

Tip
Deep recursion can hit Python's default limit of about 1,000 nested calls and raise RecursionError. sys.setrecursionlimit(10_000) raises the limit for memoized searches that need to go deeper.

partial

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:

python
1from functools import partial
2
3int16 = partial(int, base=16)
4int16("ff")                          

reduce

functools.reduce folds an iterable into a single value by applying a two-argument function cumulatively, from left to right:

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

Decorators and wraps

@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:

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

Putting It Together

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:

python
1count = 0
2for a in range(1, 7):
3    for b in range

That 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:

python
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:

python
1from functools import cache
2
3@cache
4def ways(dice, target):
5

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

)
# Return: 20
4next(it) # raises StopIteration
1
5
6list(countdown(3)) # Return: [3, 2, 1]
7
8for i in countdown(2):
9 print(i) # 2, then 1
yield
a
5 a, b = b, a + b
(
squares
)
# Return: [0, 1, 4]
3list(squares) # Return: [], already used up

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.

3[list(col) for col in zip(*grid)] # Return: [[1, 4], [2, 5], [3, 6]]
4
5pairs = [("a", 1), ("b", 2)]
6names, nums = zip(*pairs) # names = ('a', 'b'), nums = (1, 2)
str
.
isdigit
,
[
"1"
,
"x"
,
"3"
]
)
)
# Return: ['1', '3']
max
(
words
,
key
=
len
)
# Return: 'ccc'
4sorted([3, 1, 2], reverse=True) # Return: [3, 2, 1]
sorted
(
ips
,
key
=
lambda
ip
:
[
int
(
o
)
for
o
in
ip
.
split
(
"."
)
]
)
5# Return: ['10.0.0.5', '10.0.0.9', '10.0.0.12']
3all(n % 2 == 0 for n in nums) # Return: False
4sum(n > 5 for n in nums) # Return: 2, counting with booleans
list
(
it
.
permutations
(
"abc"
,
2
)
)
5# Return: [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
6
7list(it.combinations("abcd", 2))
8# Return: [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
9
10list(it.combinations_with_replacement("ab", 2))
11# Return: [('a', 'a'), ('a', 'b'), ('b', 'b')]
it
.
islice
(
it
.
cycle
(
"ab"
)
,
5
)
)
# Return: ['a', 'b', 'a', 'b', 'a']
3list(it.islice(fibonacci(), 10)) # Return: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
list
(
it
.
chain
.
from_iterable
(
[
[
1
,
2
]
,
[
3
,
4
]
]
)
)
# Return: [1, 2, 3, 4], flattening one level
3list(it.pairwise([1, 4, 9, 16])) # Return: [(1, 4), (4, 9), (9, 16)]
4list(it.batched("abcdefg", 3)) # Return: [('a', 'b', 'c'), ('d', 'e', 'f'), ('g',)]
5list(it.zip_longest("ab", "xyz", fillvalue="-")) # Return: [('a', 'x'), ('b', 'y'), ('-', 'z')]
list
(
it
.
accumulate
(
[
3
,
1
,
4
,
1
,
5
]
,
max
)
)
# Return: [3, 3, 4, 4, 5]
# Return: [('a', 3), ('b', 1), ('c', 2), ('d', 2)]
if
n
<
2
else
fib
(
n
-
1
)
+
fib
(
n
-
2
)
6
7fib(100) # Return: 354224848179261915075
# Return: 255
5list(map(int16, ["ff", "10"])) # Return: [255, 16]
3
,
4
]
)
# Return: 24, ((1 * 2) * 3) * 4
5
def
wrapper
(
*
args
,
**
kwargs
)
:
6 print(f"calling {func.__name__}{args}")
7 return func(*args, **kwargs)
8 return wrapper
9
10@logged
11def add(a, b):
12 return a + b
13
14add(2, 3) # Console: calling add(2, 3)
(
1
,
7
)
:
4 for c in range(1, 7):
5 if a + b + c == 10:
6 count += 1
7
8count # Return: 27
1
,
7
)
,
repeat
=
3
)
)
# Return: 27
if
dice
==
0
:
6 return 1 if target == 0 else 0
7 return sum(ways(dice - 1, target - face) for face in range(1, 7))
8
9ways(3, 10) # Return: 27
10ways(100, 350) # answers instantly; product would need 6 ** 100 rolls