How can I get the Cartesian product (every possible combination of values) from a group of lists?
Input:
somelists = [
[1, 2, 3],
['a', 'b'],
[4, 5]
]
Desired output:
[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...]
Just to add a bit to what has already been said: if you use sympy, you can use symbols rather than strings which makes them mathematically useful.
About sympy.
A minor modification to the above recursive generator solution in variadic flavor:
And of course a wrapper which makes it work exactly the same as that solution:
with one trade-off: it checks if recursion should break upon each outer loop, and one gain: no yield upon empty call, e.g.
product(())
, which I suppose would be semantically more correct (see the doctest).Regarding list comprehension: the mathematical definition applies to an arbitrary number of arguments, while list comprehension could only deal with a known number of them.
In Python 2.6+
Documentation: Python 3 - itertools.product
Here is a recursive generator, which doesn't store any temporary lists
Output:
Although there are many answers already, I would like to share some of my thoughts:
Iterative approach
Recursive Approach
Lambda Approach