Python itertools: 5 Functions That'll Make You Write Cleaner Loops
I used to write nested loops everywhere. Then I discovered itertools. Here are 5 functions that changed how I write Python.
1. product — Replace Nested Loops
Instead of:
for x in range(10):
for y in range(10):
for z in range(10):
process(x, y, z)
Write:
from itertools import product
for x, y, z in product(range(10), repeat=3):
process(x, y, z)
2. chain — Iterate Multiple Lists as One
from itertools import chain
for item in chain(list_a, list_b, list_c):
print(item)
No more list_a + list_b + list_c that creates a new list just to iterate.
3. groupby — Group Sorted Data
from itertools import groupby
data = [("dev", 3), ("dev", 7), ("ops", 2), ("ops", 5)]
for key, group in groupby(data, key=lambda x: x[0]):
values = [v for _, v in group]
print(f"{key}: total={sum(values)}")
Pro tip: groupby only works on sorted data. Sort first or use dict.setdefault for unsorted data.
4. combinations and permutations — Generate Possibilities
from itertools import combinations
teams = ["alpha", "beta", "gamma", "delta"]
for pair in combinations(teams, 2):
print(f"{pair[0]} vs {pair[1]}")
Handy for testing, scheduling, or any pairing problem.
5. islice — Slice Iterators Without Loading Everything
from itertools import islice
# Process first 100 lines without loading the whole file
for line in islice(open("large_file.txt"), 100):
process(line)
No memory explosion, no indexing into a generator.
When Not to Use itertools
- Your data fits in memory and you need random access → lists are fine.
- You only have one or two items → tuple unpacking is clearer.
- You're building a one-off script → readability wins.
But for data pipelines, combinatorial logic, and memory-sensitive code, itertools is your best friend.
Want more Python automation patterns like these? I put together a pack of 50 production-ready Python scripts covering file processing, API automation, data export, and system monitoring. Check it out here.
What's your go-to itertools function? I'm partial to tee for parallel iteration over a single generator.
Top comments (0)