Itertools.product() in Python

In this tutorial, we are gonna learn about itertools.product() in Python. Firstly we are going to discuss Itertools. Itertools is a Python module used to make iterator blocks by various methods. There are generally 3 types of iterators: –

  1. Infinite Iterators- Like count(), cycle(), repeat().
  2. Iterators terminating on the shortest sequence- Like groupby(), imap().
  3. Combinatorics Generator- Like permutations(), combinations().

We are going to discuss about itertools.product in this tutorial which is a combinatorics generator. We use this tool in order to find the Cartesian Product of two sets and find all the possible pairs in the form of a tuple (x,y), where x belongs to one set and y belongs to another. Cartesian products can also be implemented using for loop but it is less efficient and is harder to code than itertools.

Itertools.Product() Implementation

Firstly we import product from itertools.

Code: –

from itertools import product

After that we create two arrays and apply the product function making it a list and then we print.

Code: –



Code Output: –

[(1, 7), (1, 8), (1, 9), (1, 10), (2, 7), (2, 8), (2, 9), (2, 10), (3, 7), (3, 8), (3, 9), (3, 10), (4, 7), (4, 8), (4, 9), (4, 10), (5, 7), (5, 8), (5, 9), (5, 10), (6, 7), (6, 8), (6, 9), (6, 10)]

We see that our output is in the order in which we give input and it prints out all the possible tuples.

Example for string: –


Code Output: –

[('asd', 'rty'), ('asd', 'fgh'), ('asd', 'vbn'), ('qwe', 'rty'), ('qwe', 'fgh'), ('qwe', 'vbn'), ('zxc', 'rty'), ('zxc', 'fgh'), ('zxc', 'vbn')]

This is how we use itertools.product.

Also read: –

itertools.combinations() in Python

Leave a Reply

Your email address will not be published. Required fields are marked *