ʞɔıu ʞɔıu - 20 days ago 12
Python Question

Get the cartesian product of a series of lists in Python

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) ...]

Answer

In Python 2.6+

import itertools
for element in itertools.product(*somelists):
    print element

Documentation: Python 2 - itertools.product