Skip to content

Use `itertools.product`

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

Sourcery refactoring id: use-itertools-product

Section titled “Sourcery refactoring id: use-itertools-product”

Replaces a nested for loop over independent iterables with itertools.product. This refactoring won’t be activated if either iterable is a literal such as a list, tuple, or set.

width = 600
height = 400
i_max, j_max = (0, 0)
for i in range(width):
for j in range(height):
if pixels[i, j] > pixels[i_max, j_max]:
i_max, j_max = i, j
import itertools
width = 600
height = 400
i_max, j_max = (0, 0)
for i, j in itertools.product(range(width), range(height)):
if pixels[i, j] > pixels[i_max, j_max]:
i_max, j_max = i, j

The itertools product simplifies repeated for loops into a single iterator. This shortens the code, removes one level of nesting, collects together related variables (facilitating refactoring), and has better semantics (c.f. Cartesian product) in a number of applications (such as grid operations as in the example above).

See also: itertools.combinations