Python Advanced
Python itertools Module
The itertools module provides fast, memory-efficient building blocks for working with iterators, from infinite counters to combinations and permutations.
count() and cycle()
count() produces an infinite sequence of numbers starting from a given value, and cycle() repeats a sequence forever. Both are typically used with a limiting function like itertools.islice or a break condition.
from itertools import count, cycle, islice
for n in islice(count(10, 2), 5):
print(n, end=" ")
print()
colors = cycle(["red", "green", "blue"])
for _ in range(5):
print(next(colors), end=" ")chain() — Joining Iterables
chain() lets you loop over several iterables as if they were one continuous sequence, without copying them into a new combined list.
from itertools import chain
list1 = [1, 2, 3]
list2 = [4, 5, 6]
for n in chain(list1, list2):
print(n, end=" ")combinations() and permutations()
combinations() gives every possible unordered grouping of a given size, while permutations() gives every possible ordered arrangement. Both are extremely useful for algorithm practice and probability problems.
from itertools import combinations, permutations
items = ["A", "B", "C"]
print(list(combinations(items, 2)))
print(list(permutations(items, 2)))groupby() — Grouping Consecutive Items
groupby() groups consecutive items that share the same key. It only groups items that are next to each other, so the input is usually sorted first for meaningful grouping.
from itertools import groupby
words = ["apple", "avocado", "banana", "berry", "cherry"]
for letter, group in groupby(words, key=lambda w: w[0]):
print(letter, list(group))groupby() only groups adjacent matching items — always sort your data by the same key first, or you will get repeated groups.
| Function | Purpose |
|---|---|
| count(start, step) | Infinite arithmetic sequence |
| cycle(iterable) | Repeats an iterable forever |
| chain(a, b, ...) | Joins multiple iterables into one |
| combinations(iterable, r) | Unordered groupings of size r |
| permutations(iterable, r) | Ordered arrangements of size r |
| groupby(iterable, key) | Groups consecutive matching items |
