The Python itertools module contains many useful iterator functions. This entry will focus on the combinatoric iterators.

Today I solved the advent of code puzzle using nested for loops to iterate over each item in an array twice:

for i in data_list:
    for j in data_list:
        if i + j == 2020:
            print(i * j)

This nested for loop is finding the “cartesian product” of the the arrays it is looping over. It finds the set of all ordered pairs that can be constructed from the two arrays. The operation can be done more efficiently and succinctly by using ‘itertools.product()’.

for n in itertools.product(data_list, data_list): 
    if sum(n) == 2020: 
        print(np.product(n))

The itertools module also has functions for combinations and permutations as well:

Iterator

Arguments

Results

product()

p, q, … [repeat=1]

cartesian product, equivalent to a nested for-loop

permutations()

p[, r]

r-length tuples, all possible orderings, no repeated elements

combinations()

p, r

r-length tuples, in sorted order, no repeated elements

combinations_with_replacement()

p, r

r-length tuples, in sorted order, with repeated elements

Examples

Results

product('ABCD', repeat=2)

AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD

permutations('ABCD', 2)

AB AC AD BA BC BD CA CB CD DA DB DC

combinations('ABCD', 2)

AB AC AD BC BD CD

combinations_with_replacement('ABCD', 2)

AA AB AC AD BB BC BD CC CD DD

Python itertools docs

Updated: