itertools

Tools for working with iterators: chaining, grouping, combinations, and infinite sequences.

On this page

Example

#
Python
from itertools import chain, combinations, count, islice

print(list(chain([1, 2], [3], [4, 5])))
print(list(combinations(["HTML", "CSS", "JS"], 2)))
print(list(islice(count(10, 5), 4)))
Resultsaved result, you can check it
[1, 2, 3, 4, 5]
[('HTML', 'CSS'), ('HTML', 'JS'), ('CSS', 'JS')]
[10, 15, 20, 25]

Definition and usage

#

The itertools module contains functions that create and transform iterators. They return items lazily, one at a time, so they work well even with large and even infinite sequences of data. You go through the result with a for loop, or turn it into a list with list().

For joining and trimming there are chain() (several collections one after another), islice() (a slice from an iterator), and batched() (splitting into batches of n items, since Python 3.12). Combinatorics is handled by product(), permutations(), and combinations(), and accumulate() computes running totals.

The functions count(), cycle(), and repeat() create infinite sequences, so combine them with something that ends the loop, e.g. islice() or zip(). groupby() groups only consecutive items with the same key, so the data must first be sorted by that key.

Syntax

#
Syntax
from itertools import chain, combinations, groupby, islice

chain(*iterables)
combinations(iterable, r)
groupby(iterable, key=None)
islice(iterable, stop)

More examples

#
groupby() on sorted data
Python
from itertools import groupby

tasks = [("HTML", "1_1"), ("CSS", "2_1"), ("HTML", "1_2"), ("CSS", "2_2")]
tasks.sort(key=lambda task: task[0])

for course, group in groupby(tasks, key=lambda task: task[0]):
    print(course, [number for _, number in group])
Resultsaved result, you can check it
CSS ['2_1', '2_2']
HTML ['1_1', '1_2']
Batches, running totals, and a Cartesian product
Python
from itertools import accumulate, batched, product

print(list(batched(["1_1", "1_2", "1_3", "1_4", "1_5"], 2)))
print(list(accumulate([120, 80, 45, 200])))
print(list(product("AB", [1, 2])))
Resultsaved result, you can check it
[('1_1', '1_2'), ('1_3', '1_4'), ('1_5',)]
[120, 200, 245, 445]
[('A', 1), ('A', 2), ('B', 1), ('B', 2)]

Good practices

#
  • An iterator from itertools can be traversed only once. If you need the result several times, save it as a list.
  • Sort the data by the same key before groupby(). Otherwise the same key will show up in several separate groups.
  • Do not call list() on count() or cycle(). They are infinite sequences that will hang the program.

Related entries

#

Spotted a mistake or missing an example? Write to us.