Python itertools
last modified November 29, 2026 Python 3.15
In this article we show how to use the itertools module in
Python.
The itertools module contains functions that build iterators.
Each function takes one or more iterables and returns a lazy iterator: it
produces values one at a time, only when they are requested. The functions
can be combined into pipelines that process long or even infinite streams
without building intermediate lists.
Several parts of the module have their own articles. The infinite
iterators count, cycle, and repeat
are covered in Python infinite
iterators, chain in Python
chain, and groupby in Python
groupby. This article covers the rest.
Taking the first items
Iterators do not support the slice syntax [start:stop]. The
islice function does the same job for any iterable, including
an infinite one.
from itertools import islice, count
squares = (n * n for n in count(1))
print(list(islice(squares, 5)))
print(list(islice('abcdefgh', 2, 6)))
print(list(islice(range(20), 0, 20, 5)))
The generator expression produces squares forever, and islice
stops after five of them. With three arguments, islice takes
the items from index 2 up to, but not including, index 6. The fourth
argument is a step. Negative indexes are not supported, because an
iterator does not know its length in advance.
$ python first_islice.py [1, 4, 9, 16, 25] ['c', 'd', 'e', 'f'] [0, 5, 10, 15]
Iterators are consumed
An iterator remembers its position. Every item that a function takes from it is gone; a list, on the other hand, creates a new iterator each time it is iterated.
from itertools import islice words = iter(['alpha', 'beta', 'gamma', 'delta', 'epsilon']) print(list(islice(words, 2))) print(list(islice(words, 2))) print(list(words)) numbers = [1, 2, 3, 4, 5] print(list(islice(numbers, 2))) print(list(islice(numbers, 2)))
The two islice calls on the same iterator return different
items: the second call continues where the first stopped, and
list collects whatever remains. The same calls on a list
start from the beginning each time. This behaviour is important for every
function in the module, and it is often useful: we can take a header
from an iterator and then process the rest.
$ python consumed.py ['alpha', 'beta'] ['gamma', 'delta'] ['epsilon'] [1, 2] [1, 2]
Splitting data into batches
The batched function, added in Python 3.12, groups items into
tuples of a given size. The last tuple can be shorter.
from itertools import batched
orders = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7']
for batch in batched(orders, 3):
print(batch)
lines = ['name', 'Ann', 'age', '34', 'city', 'Brno']
print(dict(batched(lines, 2)))
try:
print(list(batched(orders, 2, strict=True)))
except ValueError as e:
print('error:', e)
The seven orders are processed in batches of three, for example to send
them to a server in fewer requests. Batches of two turn a flat list of
keys and values into a dictionary. With strict=True,
available since Python 3.13, an incomplete last batch raises a
ValueError.
$ python batches.py
('A1', 'A2', 'A3')
('A4', 'A5', 'A6')
('A7',)
{'name': 'Ann', 'age': '34', 'city': 'Brno'}
error: batched(): incomplete batch
Consecutive pairs
The pairwise function returns overlapping pairs of
neighbouring items: the first and second, the second and third, and so on.
from itertools import pairwise
readings = [12.0, 12.5, 14.0, 13.5, 15.5]
for prev, cur in pairwise(readings):
print(f'{prev} -> {cur}: {cur - prev:+.1f}')
print(list(pairwise('abcd')))
towns = ['Bratislava', 'Trnava', 'Nitra', 'Zvolen']
print([f'{a}-{b}' for a, b in pairwise(towns)])
The differences between consecutive temperature readings are computed without any indexes. A sequence of n items gives n - 1 pairs; the list of towns becomes a list of route segments. An iterable with fewer than two items gives no pairs.
$ python pairs.py
12.0 -> 12.5: +0.5
12.5 -> 14.0: +1.5
14.0 -> 13.5: -0.5
13.5 -> 15.5: +2.0
[('a', 'b'), ('b', 'c'), ('c', 'd')]
['Bratislava-Trnava', 'Trnava-Nitra', 'Nitra-Zvolen']
Running totals
The accumulate function returns running results. By default
it adds; another two-argument function can be passed to combine the items
in a different way.
from itertools import accumulate import operator sales = [120, 80, 200, 50, 150] print(list(accumulate(sales))) print(list(accumulate(sales, initial=1000))) print(list(accumulate(sales, max))) print(list(accumulate([1, 2, 3, 4, 5], operator.mul))) balance = 100 changes = [-30, 50, -90, 20] print(list(accumulate(changes, initial=balance)))
The first line shows the cumulative sales. The initial value
is placed in front of the results, so there is one more item. With
max, we get the highest value seen so far, and with
operator.mul the factorials 1! to 5!. The last example
follows an account balance after each deposit and withdrawal.
$ python running.py [120, 200, 400, 450, 600] [1000, 1120, 1200, 1400, 1450, 1600] [120, 120, 200, 200, 200] [1, 2, 6, 24, 120] [100, 70, 120, 30, 50]
takewhile and dropwhile
The takewhile function returns items while a predicate is
true and stops at the first item for which it is false.
dropwhile does the opposite: it skips items while the
predicate is true and then returns everything else.
from itertools import takewhile, dropwhile
log = [
'# generated by sensor 7',
'# units: celsius',
'21.5',
'22.0',
'# recalibrated',
'21.8',
]
header = list(takewhile(lambda line: line.startswith('#'), log))
data = list(dropwhile(lambda line: line.startswith('#'), log))
print(header)
print(data)
print([x for x in log if not x.startswith('#')])
The log starts with comment lines. takewhile returns the
header, and dropwhile returns the data that follows it.
Neither function tests items after the first change: the comment
'# recalibrated' stays in the data. To remove every comment
line, a filter or a list comprehension is needed, as the last line shows.
$ python while_funcs.py ['# generated by sensor 7', '# units: celsius'] ['21.5', '22.0', '# recalibrated', '21.8'] ['21.5', '22.0', '21.8']
filterfalse and compress
The filterfalse function is the complement of the built-in
filter: it keeps the items for which the predicate is false.
The compress function selects items using a second iterable
of flags.
from itertools import filterfalse, compress
numbers = [4, 7, 10, 13, 16, 19]
def is_even(n):
return n % 2 == 0
print(list(filter(is_even, numbers)))
print(list(filterfalse(is_even, numbers)))
products = ['pen', 'ink', 'paper', 'clip']
in_stock = [True, False, True, True]
print(list(compress(products, in_stock)))
With the same predicate, filter returns the even numbers and
filterfalse the odd ones. compress pairs each
product with the flag at the same position and keeps the products whose
flag is true. The flags often come from another column of data, so no
predicate function is needed.
$ python selecting.py [4, 10, 16] [7, 13, 19] ['pen', 'paper', 'clip']
starmap
The starmap function calls a function with arguments unpacked
from each item. Where map takes the arguments from several
iterables in parallel, starmap takes them from one iterable
of tuples.
from itertools import starmap
rectangles = [(3, 4), (5, 2), (10, 1)]
print(list(starmap(lambda w, h: w * h, rectangles)))
print(list(map(pow, [2, 3, 10], [5, 2, 3])))
print(list(starmap(pow, [(2, 5), (3, 2), (10, 3)])))
items = [('apples', 3, 0.5), ('pears', 2, 0.8)]
for line in starmap('{}: {} x {:.2f}'.format, items):
print(line)
Each rectangle is a tuple of width and height, and the lambda receives
them as two separate arguments. The two pow lines compute the
same values from differently shaped data. The bound method
str.format also works as the function, which formats each
tuple into a line.
$ python star_map.py [12, 10, 10] [32, 9, 1000] [32, 9, 1000] apples: 3 x 0.50 pears: 2 x 0.80
zip_longest
The built-in zip stops at the shortest iterable.
zip_longest continues until the longest one is exhausted and
fills in the missing values.
from itertools import zip_longest
names = ['Ann', 'Bob', 'Cyril', 'Dana']
scores = [88, 92]
print(list(zip(names, scores)))
print(list(zip_longest(names, scores)))
print(list(zip_longest(names, scores, fillvalue=0)))
try:
print(list(zip(names, scores, strict=True)))
except ValueError as e:
print('error:', e)
Only two of the four students have scores. zip silently drops
Cyril and Dana, while zip_longest keeps them with
None or with the given fillvalue. When the
iterables are expected to have the same length, zip with
strict=True reports the mismatch as an error.
$ python longest.py
[('Ann', 88), ('Bob', 92)]
[('Ann', 88), ('Bob', 92), ('Cyril', None), ('Dana', None)]
[('Ann', 88), ('Bob', 92), ('Cyril', 0), ('Dana', 0)]
error: zip() argument 2 is shorter than argument 1
Copying an iterator with tee
Since an iterator can be consumed only once, two loops cannot read the
same iterator independently. The tee function splits one
iterator into several independent ones.
from itertools import tee
def read_values():
print('reading')
yield from [3, 1, 4, 1, 5]
first, second = tee(read_values())
print(max(first))
print(sum(second))
values = iter(range(5))
a, b = tee(values)
next(values)
print(list(a), list(b))
The generator is read only once, as the single reading line
shows, yet both max and sum see all values.
tee keeps the items that one copy has seen and the other has
not yet in memory. After calling tee, the original iterator
must not be used: in the second example, next takes 0 from it,
and both copies miss that value. If one copy is read completely before the
other, a list is simpler and faster.
$ python teeing.py reading 5 14 [1, 2, 3, 4] [1, 2, 3, 4]
Cartesian product
The product function returns all combinations of one item from
each iterable. It replaces nested for loops.
from itertools import product
sizes = ['S', 'M']
colors = ['red', 'blue', 'green']
for size, color in product(sizes, colors):
print(size, color)
print(list(product('01', repeat=3)))
print(len(list(product(range(10), repeat=4))))
Two sizes and three colours give six variants of a product, in the same
order as two nested loops would produce them. The repeat
argument uses the same iterable several times: three binary digits give
eight tuples. The number of results grows quickly; four decimal digits
already give ten thousand.
$ python products.py
S red
S blue
S green
M red
M blue
M green
[('0', '0', '0'), ('0', '0', '1'), ('0', '1', '0'), ('0', '1', '1'), ('1', '0', '0'), ('1', '0', '1'), ('1', '1', '0'), ('1', '1', '1')]
10000
Permutations and combinations
The permutations function returns ordered arrangements of
items, and combinations returns selections where the order
does not matter. combinations_with_replacement allows an item
to be selected more than once.
from itertools import permutations, combinations
from itertools import combinations_with_replacement
import math
team = ['Ann', 'Bob', 'Cyril']
print(list(permutations(team, 2)))
print(list(combinations(team, 2)))
print(list(combinations_with_replacement('ab', 2)))
print(math.perm(10, 3), len(list(permutations(range(10), 3))))
print(math.comb(10, 3), len(list(combinations(range(10), 3))))
From three people we can form six ordered pairs, for example a captain and
a deputy, but only three unordered teams of two. Items are treated as
distinct by their position, not their value. The math.perm and
math.comb functions count the results without generating
them, which is the better choice when only the number is needed.
$ python choosing.py
[('Ann', 'Bob'), ('Ann', 'Cyril'), ('Bob', 'Ann'), ('Bob', 'Cyril'), ('Cyril', 'Ann'), ('Cyril', 'Bob')]
[('Ann', 'Bob'), ('Ann', 'Cyril'), ('Bob', 'Cyril')]
[('a', 'a'), ('a', 'b'), ('b', 'b')]
720 720
120 120
Choosing items within a budget
The combinatoric functions are useful for small search problems. In this example, we look for the set of items that comes closest to a budget without exceeding it.
from itertools import combinations
prices = {'book': 12, 'pen': 3, 'lamp': 25, 'mug': 8, 'plant': 15}
budget = 30
best = None
for size in range(1, len(prices) + 1):
for items in combinations(prices, size):
total = sum(prices[item] for item in items)
if total <= budget and (best is None or total > best[0]):
best = (total, items)
print(best)
Iterating over a dictionary gives its keys, so combinations
returns tuples of item names. The outer loop tries sets of one item, then
two, and so on; together the loops check all 31 non-empty subsets. The
best set costs exactly 30. This brute-force approach is fine for a handful
of items, but the number of subsets doubles with every new item.
$ python budget.py
(30, ('book', 'pen', 'plant'))
A sliding window
The module documentation lists recipes built from the basic functions. The
sliding_window recipe returns overlapping windows of a fixed
size, which generalizes pairwise.
from collections import deque
from itertools import islice
def sliding_window(iterable, n):
it = iter(iterable)
window = deque(islice(it, n - 1), maxlen=n)
for x in it:
window.append(x)
yield tuple(window)
temps = [20, 22, 21, 25, 27, 26, 24]
for w in sliding_window(temps, 3):
print(w, round(sum(w) / 3, 1))
The generator first fills a deque with n - 1
items using islice. A deque with maxlen drops its
oldest item when a new one is appended, so each step yields the current
window. The program prints a three-day moving average of temperatures.
More recipes are packaged in the third-party more-itertools
library.
$ python window.py (20, 22, 21) 21.0 (22, 21, 25) 22.7 (21, 25, 27) 24.3 (25, 27, 26) 26.0 (27, 26, 24) 25.7
Source
itertools – Functions creating iterators for efficient looping, Itertools recipes, more-itertools
In this article we have sliced iterators with islice, split data with batched, walked neighbouring items with pairwise and a sliding window, computed running totals with accumulate, filtered with takewhile, dropwhile, filterfalse, and compress, and generated products, permutations, and combinations. See also Python iterators, Python generators, Python lazy evaluation, and Python operator module.
Author
List all Python tutorials.