Skip to content

Use itertools.product

Sourcery refactoring id: use-itertools-product

Description

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.

Before

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

After

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

Explanation

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

Back to top