Given Python lists A and B, the Cartesian product of the two lists is the set of all ordered pairs (a, b) such that a is an element of A and b is an element of B . In mathematical notation, this is denoted:
We can write a more general definition of the Cartesian product for n lists :
Here I show three methods for producing Cartesian products of lists in Python: The first is through nested for-loops, the second through the itertools package using an explicit list of lists as arguments, and the third though the itertools package using a pointer to a variable containing a set of lists which can be modified during runtime.
The first way to obtain the Cartesian product of a given set of lists is to use nested for loops, which works well if you already know the number of lists in the set, and there are only a few lists to consider:
The advantage of this approach is that the code is easy to understand. However, this approach does not scale well when the number of lists in the set gets large (who wants deeply nested for loops?).
A better method is to use the itertools.product function, which takes the lists as arguments and produces an iterator for each Cartesian product element:
However, this requires that you know the arguments to itertools.product beforehand. Suppose instead that you have the lists you want included in the Cartesian product stored in a list variable called “sets”, which may vary in size and content during runtime. In this case you can simply give itertools.product a pointer to the list of lists: