📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Python from Zero Itertools

Itertools

6 min read
itertools provides efficient iterator tools: chain() combines iterables, groupby() groups consecutive items, and combinations() creates combinatorial sequences. All values are produced lazily on demand.

itertools Module

from itertools import chain, combinations, permutations, groupby

# Chain iterables
list(chain([1,2], [3,4]))    # [1,2,3,4]

# Combinations
list(combinations("ABC", 2)) # [(A,B),(A,C),(B,C)]

# Permutations
list(permutations([1,2,3]))  # all orderings

# Groupby
data = sorted([{'type':'a'},{'type':'b'},{'type':'a'}], key=lambda x: x['type'])
for key, grp in groupby(data, lambda x: x['type']):
    print(key, list(grp))