The itertools Module in 3 Quick Examples

Published:
Last updated:
By Jeferson Peter
Python

Imagine you need to generate infinite sequences, repeat values in a loop, or find all possible pairs from a list.
Instead of reinventing the wheel, Python’s built-in itertools module has you covered. Let’s explore three handy tools.


Example 1: count()

from itertools import count

for i in count(10, 2):
    print(i)
    if i > 20:
        break

# 10
# 12
# 14
# 16
# 18
# 20

Generates an infinite sequence starting from 10, stepping by 2.


Example 2: cycle()

from itertools import cycle

colors = ["red", "green", "blue"]
for i, color in enumerate(cycle(colors)):
    if i > 5:
        break
    print(color)

# red
# green
# blue
# red
# green
# blue

Repeats elements from a list indefinitely.


Example 3: combinations()

from itertools import combinations

items = ["A", "B", "C"]
for combo in combinations(items, 2):
    print(combo)

# ('A', 'B')
# ('A', 'C')
# ('B', 'C')

Generates all possible pairs from the list.


Conclusion

itertools provides efficient iteration tools, perfect for working with sequences, loops, and combinations without writing extra code.