12. Product of lists

Here’s how to get the product of elements in multiple lists.

itertools.product names the Cartesian product directly, which is clearer than nested loops once the number of input iterables grows. It also scales better conceptually because the code shape stays the same as you add dimensions.

12.1. Don’t do this

 1a = ['cat', 'dog', 'frog']
 2b = ['red', 'green', 'blue']
 3c = ['big', 'small']
 4
 5product_list = []
 6for animal in a:
 7    for color in b:
 8        for size in c:
 9            tup = animal, color, size
10            product_list.append(tup)

12.2. Do this

1from itertools import product
2
3a = ['cat', 'dog', 'frog']
4b = ['red', 'green', 'blue']
5c = ['big', 'small']
6
7product_list = product(a, b, c)
1from itertools import product
2
3a = ['cat', 'dog', 'frog']
4b = ['red', 'green', 'blue']
5c = ['big', 'small']
6
7list_of_list = [a, b, c]
8product_list = product(*list_of_list)