product

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', 'Mopsy', 'Bea')
('Benjamin', 'Mopsy', 'Thomas')
('Benjamin', 'Mopsy', 'McGregor')
('Benjamin', 'Cottontail', 'Bea')
('Benjamin', 'Cottontail', 'Thomas')
('Benjamin', 'Cottontail', 'McGregor')
('Benjamin', 'Flopsy', 'Bea')
('Benjamin', 'Flopsy', 'Thomas')
('Benjamin', 'Flopsy', 'McGregor')

As you can see, the product function generates all the permutations of the elements from three sets.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset