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) ...]
For Python 2.5 and older:
Here's a recursive version of
product()
(just an illustration):Example:
I would use list comprehension :
In Python 2.6 and above you can use 'itertools.product`. In older versions of Python you can use the following (almost -- see documentation) equivalent code from the documentation, at least as a starting point:
The result of both is an iterator, so if you really need a list for furthert processing, use
list(result)
.with itertools.product: