Welcome to Day 34 of your Python journey!
Today, we’ll dive into one of Python’s most powerful standard libraries: itertools
.
If you’ve ever wanted to:
- generate combinations,
- create infinite sequences,
- or chain multiple iterables,
…then itertools
is your best friend.
🧰 What is itertools
?
The itertools
module provides a collection of fast, memory-efficient tools that work on iterators and help you loop like a pro.
🔢 1. Infinite Iterators
These functions produce data endlessly (until you stop them).
count(start=0, step=1)
from itertools import count
for i in count(10, 2):
print(i)
if i > 20:
break
Output: 10, 12, 14, 16, 18, 20, 22
cycle(iterable)
Loops through an iterable forever.
from itertools import cycle
for item in cycle(['A', 'B', 'C']):
print(item)
break # Use `break` to stop it
repeat(item, times)
Repeats the same item a number of times.
from itertools import repeat
for item in repeat('Hello', 3):
print(item)
Output:
Hello
Hello
Hello
🔁 2. Combinatoric Iterators
Perfect for generating permutations, combinations, and Cartesian products.
product()
from itertools import product
colors = ['red', 'blue']
sizes = ['S', 'M']
for combo in product(colors, sizes):
print(combo)
Output:
('red', 'S')
, ('red', 'M')
, ('blue', 'S')
, ('blue', 'M')
permutations(iterable, r=None)
All possible ordered arrangements.
from itertools import permutations
for p in permutations([1, 2, 3], 2):
print(p)
combinations(iterable, r)
All possible unordered combinations.
from itertools import combinations
for c in combinations([1, 2, 3], 2):
print(c)
🔗 3. Utility Iterators
Useful tools for filtering, chaining, slicing, and grouping iterables.
chain()
Joins multiple iterables together.
from itertools import chain
for i in chain([1, 2], ['A', 'B']):
print(i)
islice()
Slices an iterator like a list.
from itertools import islice
for i in islice(range(100), 10, 15):
print(i)
Output: 10, 11, 12, 13, 14
compress(data, selectors)
Filters data by truthy values in selectors
.
from itertools import compress
data = 'ABCDEF'
selectors = [1, 0, 1, 0, 1, 0]
print(list(compress(data, selectors))) # ['A', 'C', 'E']
📌 Real Use Cases
Task |
itertools Function |
---|---|
Generate all outfit combos | product() |
Slice big data | islice() |
Infinite loop through status | cycle() |
Vote tally simulation | repeat() |
Schedule permutations | permutations() |
🧪 Mini Practice
- Get all 3-letter permutations of "ABC".
- Generate all size-color combinations from two lists.
- Chain 3 lists into one iterator.
🧠 Pro Tip
itertools
returns iterators, not lists.
Use list()
to consume them, but remember—they are memory efficient only when you don’t convert them.