Introduction
Advanced itertools patterns for complex iterator transformations.
GroupBy
import itertools
data = [("A", 1), ("A", 2), ("B", 3), ("B", 4), ("C", 5)]
for key, group in itertools.groupby(data, key=lambda x: x[0]):
items = list(group)
print(f"{key}: {items}")
Islice
import itertools
arr = range(10)
# First 5 elements
first5 = list(itertools.islice(arr, 5))
# Skip first 3, take next 4
subset = list(itertools.islice(arr, 3, 7))
# Infinite with islice
infinite = itertools.count()
even = itertools.islice(infinite, 0, 10, 2) # 0, 2, 4, 6, 8
Zip Longest
import itertools
# Different lengths
a = [1, 2, 3]
b = ["a", "b"]
list(itertools.zip_longest(a, b, fillvalue=None))
# [(1, 'a'), (2, 'b'), (3, None)]
Practice Problems
- Window sliding with islice
- Merge overlapping intervals
- Group by multiple keys
- Pad sequences to same length
- Create lazy chunking iterator