🌀 itertools Module
Last Updated: 24th August 2025
It provides tools for creating iterators (objects you can loop over) in a very efficient way.
List of Functions:
- itertools.combinations(iterable, r): Returns an iterator over all combinations of length r in iterable.
import itertools
# example 1
students = list(range(100))
pairs = itertools.combinations(students, 2) # generator, not list
for p in pairs:
print(p)
# example 2
features = ["age", "income", "education"]
for combo in itertools.combinations(features, 2):
print(combo)
- permutations(iterable, r): Returns an iterator over all permutations of length r in iterable.
from itertools import permutations
models = ["LR", "SVM", "RF"]
for order in permutations(models, 2):
print(order)
- product(*iterables, repeat=1): Returns an iterator that computes the cartesian product of multiple iterables.
from itertools import product
colors = ["red", "green", "blue"]
sizes = ["S", "M", "L"]
for color, size in product(colors, sizes):
print(color, size) # red S, red M, red L, green S, green M, green L, blue S, blue M, blue L
- cyclic(iterable): Returns an iterator that cycles through the elements of iterable.Repeats the sequence indefinitely.
from itertools import cycle
labels = ["Train", "Test"]
cycler = cycle(labels)
for _ in range(5):
print(next(cycler))
- chain(*iterables): Returns an iterator that chains the elements of multiple iterables together.
from itertools import chain
a = [1, 2, 3]
b = [4, 4, 6]
c = [7, 6, 9]
merged = chain(a, b, c)
print(list(merged)) # [1, 2, 3, 4, 4, 6, 7, 6, 9]
- accumulate(iterable, start=0): Returns an iterator that accumulates the elements of iterable.
from itertools import accumulate
numbers = [1, 2, 3, 4, 5]
cumulative_sum = accumulate(numbers)
print(list(cumulative_sum)) # [1, 3, 6, 10, 15]
- groupby(iterable, key=None): Returns an iterator that groups elements of iterable based on the key function.
from itertools import groupby
numbers = [1, 2, 3, 4, 5]
grouped = groupby(sorted(numbers, key=lambda x: x % 2), lambda x: x % 2)
for key, group in grouped:
print(key, list(group))
- dropwhile(predicate, iterable): Returns an iterator that drops elements from the iterable while the predicate is true.
from itertools import dropwhile
temps = [28, 30, 32, 35, 29, 27]
hot_days = list(dropwhile(lambda t: t < 33, temps))
print(hot_days)
- takewhile(predicate, iterable): Returns an iterator that takes elements from the iterable while the predicate is true.
from itertools import takewhile
temps = [28, 30, 32, 35, 29, 27]
cool_days = list(takewhile(lambda t: t < 33, temps))
print(cool_days)
- filterfalse(function, iterable): It is opposite of filter function. Returns an iterator that filters out elements for which the function returns False.
from itertools import filterfalse
numbers = [1, 2, 3, 4, 5]
filtered = filterfalse(lambda x: x % 2 == 0, numbers)
print(list(filtered)) # [1, 3, 5]