Python Cartesian Product of Lists

22 Nov 2015

Loops are common program constrol structure, including nested loops. In python, there are alternative ways to write nested for-loops, which makes the indentation in your code more flat and increases readibility.

One technique is to use list comprehension (assuming lists are independent of each other), for example:

for i in l:
    for j in m:
        print (i+j)

# can be changed to:
for s in ((i+j) for i in l for j in k):
    print s

The code above is doing cartesian product of two lists, which brings us to another technique that is provided by Python standard library itertools.product:

from itertools import product

for i, j in product(l, m):
    print (i+j)

Less code, more readible; more importantly, itertools.product returns a generator/iterator, which is more memory efficient if you only want to iterate through the results. Isn’t it beautiful?