Table of Contents

import itertools

import itertools is a Python import that provides efficient iteration tools: combinations, permutations, chaining iterables, and infinite counters. Use these for combinatorics and lazy evaluation.

Example

# Python
# description: combinations, permutations, infinite count
 
import itertools
 
# Combinations (no order)
combos = itertools.combinations("ABC", 2)
print(list(combos))  # [('A', 'B'), ('A', 'C'), ('B', 'C')]
 
# Permutations (all orderings)
perms = itertools.permutations("AB", 2)
print(list(perms))  # [('A', 'B'), ('B', 'A')]
 
# Chain multiple iterables
numbers = itertools.chain([1, 2], [3, 4], [5])
print(list(numbers))  # [1, 2, 3, 4, 5]
 
# Infinite counter
counter = itertools.count(start=10, step=2)
print([next(counter) for _ in range(5)])  # [10, 12, 14, 16, 18]
 
# Repeat value
repeated = itertools.repeat("x", times=3)
print(list(repeated))  # ['x', 'x', 'x']
 
# Cycle through iterable
cycle = itertools.cycle([1, 2, 3])
print([next(cycle) for _ in range(7)])  # [1, 2, 3, 1, 2, 3, 1]

Common functions