itertools
Tools for working with iterators: chaining, grouping, combinations, and infinite sequences.
Example
#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)))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
#from itertools import chain, combinations, groupby, islice
chain(*iterables)
combinations(iterable, r)
groupby(iterable, key=None)
islice(iterable, stop)More examples
#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])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])))Good practices
#- An iterator from
itertoolscan 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()oncount()orcycle(). They are infinite sequences that will hang the program.
Related entries
#- zip()Pairs up (or groups into tuples) the matching items of several collections.
- enumerate()Adds a counter to items while looping over them.
- yieldCreates a generator: a function that returns successive values on demand.
- range()Creates a sequence of integers, most often for a for loop.
- map()Calls a function for every item and returns an iterator of results.
- functoolsTools for working with functions: remembering results (lru_cache), partial calls (partial), and folding collections (reduce).
Spotted a mistake or missing an example? Write to us.