Cartesian Product of Multiple Lists with itertools.product
To obtain the Cartesian product of a group of lists, where every possible combination of values is generated, utilize the built-in itertools.product function. This feature has been included in Python since version 2.6.
Implementation:
import itertools somelists = [ [1, 2, 3], ['a', 'b'], [4, 5] ] for element in itertools.product(*somelists): print(element)
Alternatively, you can provide separate arguments to the function like this:
for element in itertools.product([1, 2, 3], ['a', 'b'], [4, 5]): print(element)
Either approach will generate the same output:
(1, 'a', 4) (1, 'a', 5) (1, 'b', 4) (1, 'b', 5) (2, 'a', 4) (2, 'a', 5) ...
Note:
The above is the detailed content of How Can itertools.product Generate the Cartesian Product of Multiple Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!