August 2019
Beginner
482 pages
12h 56m
English
itertools.product generates a Cartesian product (a set of all permutations), a concise equivalent of a nested for loop. Here is how it appears. First, we create three sets (product can take any number of iterables):
s1 = {'Peter', 'Benjamin'}s2 = {'Flopsy', 'Mopsy', 'Cottontail'}s3 = {'McGregor', 'Thomas', 'Bea'}
Next, we call a product function on all of them, printing the result:
>>> from itertools import product>>> for el in product(s1, s2, s3): print(el)('Peter', 'Mopsy', 'Bea')('Peter', 'Mopsy', 'Thomas')('Peter', 'Mopsy', 'McGregor')('Peter', 'Cottontail', 'Bea')('Peter', 'Cottontail', 'Thomas')('Peter', 'Cottontail', 'McGregor')('Peter', 'Flopsy', 'Bea')('Peter', 'Flopsy', 'Thomas')('Peter', 'Flopsy', 'McGregor')('Benjamin', ...