Introduction
Itertools provides fast, memory-efficient tools for creating and working with iterators.
Infinite Iterators
import itertools
# Count (infinite counter)
counter = itertools.count(1, 2) # 1, 3, 5, 7, ...
next(counter) # 1
# Cycle (repeat infinitely)
cycle = itertools.cycle([1, 2, 3]) # 1, 2, 3, 1, 2, 3, ...
# Repeat
repeat = itertools.repeat("x", times=3) # x, x, x
Finite Iterators
import itertools
# Accumulate (running totals)
acc = itertools.accumulate([1, 2, 3, 4]) # 1, 3, 6, 10
# Chain (combine iterables)
chained = list(itertools.chain([1, 2], [3, 4], [5, 6]))
# Compress (filter by selector)
compressed = list(itertools.compress("ABCDEF", [1, 0, 1, 0, 1, 0]))
# Drop/Take while
dropped = list(itertools.dropwhile(lambda x: x < 3, [1, 2, 3, 4, 1]))
Combinatoric Iterators
import itertools
# Permutations (order matters)
list(itertools.permutations([1, 2, 3], 2)) # (1,2), (1,3), (2,1), (2,3), (3,1), (3,2)
# Combinations (order doesn't matter)
list(itertools.combinations([1, 2, 3], 2)) # (1,2), (1,3), (2,3)
# Product (cartesian product)
list(itertools.product([1, 2], repeat=2)) # (1,1), (1,2), (2,1), (2,2)
Practice Problems
- Generate all possible PIN combinations
- Create running maximum iterator
- Group consecutive elements with groupby
- Find all anagrams using permutations
- Build infinite Fibonacci with cycle