python - Get the cartesian product of a series of lists? -


how can cartesian product (every possible combination of values) 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) ...] 

in python 2.6+

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

documentation: python 3 - itertools.product


Comments