itertools
The Python itertools
module provides a collection of tools to perform fast and memory-efficient iteration. They make it possible to construct specialized tools succinctly and efficiently in Python.
Here’s an example:
>>> import itertools
>>> list(itertools.chain([1, 2], [3, 4], [5, 6]))
[1, 2, 3, 4, 5, 6]
Key Features
Frequently Used Classes and Functions
Object | Type | Description |
---|---|---|
itertools.count() |
Function | Creates an infinite iterator that returns evenly spaced values |
itertools.cycle() |
Function | Creates an infinite iterator that cycles through an iterable |
itertools.repeat() |
Function | Repeats an object, either infinitely or a specified number of times |
itertools.chain() |
Function | Combines multiple iterables into a single iterator |
itertools.combinations() |
Function | Produces combinations of a specified length from input iterables |
itertools.permutations() |
Function | Produces permutations of a specified length from input iterables |
itertools.product() |
Function | Computes the Cartesian product of input iterables |
Examples
Cycling through an iterable:
>>> from itertools import cycle
>>> colors = cycle(["red", "green", "blue"])
>>> [next(colors) for _ in range(6)]
['red', 'green', 'blue', 'red', 'green', 'blue']
Generating combinations of a sequence:
>>> from itertools import combinations
>>> list(combinations("ABC", 2))
[('A', 'B'), ('A', 'C'), ('B', 'C')]
Common Use Cases
- Creating infinite sequences with
count()
,cycle()
, andrepeat()
- Merging multiple iterables with
chain()
- Generating combinatorial sequences like permutations and combinations
- Efficiently processing large data streams
Real-World Example
Suppose you need to generate all possible seating arrangements for a group of people at a round table:
>>> from itertools import permutations
>>> guests = ["Alice", "Bob", "Carol"]
>>> list(permutations(guests))
[
('Alice', 'Bob', 'Carol'),
('Alice', 'Carol', 'Bob'),
('Bob', 'Alice', 'Carol'),
('Bob', 'Carol', 'Alice'),
('Carol', 'Alice', 'Bob'),
('Carol', 'Bob', 'Alice')
]
In this example, the itertools.permutations()
function provides an efficient way to generate all possible seating arrangements, demonstrating how the module can solve problems involving combinatorial logic.
Related Resources
Tutorial
Python itertools By Example
Master Python's itertools module by constructing practical examples. You'll start out simple and then gradually tackle more complex challenges, encouraging you to "think iteratively."
For additional information on related topics, take a look at the following resources:
- Python for Loops: The Pythonic Way (Tutorial)
- When to Use a List Comprehension in Python (Tutorial)
- For Loops in Python (Definite Iteration) (Course)
- Python for Loops: The Pythonic Way (Quiz)
- Understanding Python List Comprehensions (Course)
- When to Use a List Comprehension in Python (Quiz)
By Leodanis Pozo Ramos • Updated July 10, 2025