Enhancing Python Loops with itertools: cycle, chain, and combinations
Enhancing Python Loops with itertools: cycle, chain, and combinations ๐
The itertools module in Python helps you write cleaner and more powerful loops.
In this post, we'll explore three essential functions: cycle(), chain(), and combinations(), all with real-world examples.
✅ cycle(): Infinite Looping
Repeats the items in a list forever. Great for rotation patterns or cycling states.
from itertools import cycle
colors = ['red', 'green', 'blue']
cycler = cycle(colors)
for _ in range(6):
print(next(cycler))
✅ chain(): Merging Lists
Combine multiple lists into a single iterable for streamlined processing.
from itertools import chain
a = [1, 2]
b = [3, 4]
c = [5]
combined = list(chain(a, b, c))
print(combined)
✅ combinations(): Generating All Combos
Creates all possible combinations of items. Perfect for search, pairing, or testing.
from itertools import combinations
items = ['A', 'B', 'C']
for combo in combinations(items, 2):
print(combo)
With itertools, you can replace many lines of manual loop logic with one clean, efficient call.
Whether you're writing algorithms, handling data, or building automation, mastering these tools pays off fast.
Don’t just repeat — iterate smarter. With itertools, every loop becomes a tool for clarity and control. ๐
Icons by Flaticon
Comments
Post a Comment