🐍 Python Once a Week
Double For Loops2019-11-09

Sometimes double for loops are unavoidable. Visually, indenting double for loops could lead to a lot of undesirable nesting. I find this particularly true when you introduce flow-control within the loop. To replace most double for loops you could use itertools.product.

first_sequence = range(100)
second_sequence = range(100)

for x in first_sequence:
    for y in second_sequence:
        # do work
        pass

# now becomes
import itertools

for x, y in itertools.product(first_sequence, second_sequence):
    # do work
    pass

Note, itertools.product(A, B) is also equivalent to the list comprehension ((x,y) for x in A for y in B) . I'll cover comprehensions in another weekly tip!

The python std modules are a great reference for this https://docs.python.org/3.8/library/itertools.html#itertools.product.