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:

Python
>>> import itertools
>>> list(itertools.chain([1, 2], [3, 4], [5, 6]))
[1, 2, 3, 4, 5, 6]

Key Features

  • Provides building blocks for creating iterators
  • Facilitates efficient iteration
  • Contains functions to create infinite iterators
  • Offers tools for combinatorics

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:

Python
>>> 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:

Python
>>> from itertools import combinations
>>> list(combinations("ABC", 2))
[('A', 'B'), ('A', 'C'), ('B', 'C')]

Common Use Cases

  • Creating infinite sequences with count(), cycle(), and repeat()
  • 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:

Python
>>> 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.

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."

advanced python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated July 10, 2025