What is the itertools.product() method in Python?

Overview

In Python, itertools is a module in Python that provides functions. These functions help in iterating through iterables.

The product() method of the itertools module returns the cartesian product of the input iterables. The method takes an optional argument called repeat, which when used returns the cartesian product of the iterable with itself for the number of times specified in the repeat parameter.

Let’s refer to the coding example below to understand more.

Syntax

itertools.product(*iterables, repeat=1)

Parameters

  • *iterables: The list of iterables.
  • repeat: An integer argument that returns the cartesian product of the iterable with itself for the number of times specified.

Example

from itertools import product
lst = [1,2,3,4,5]
print("Original list - ", lst)
print("Cartesian product of the list with itself - ", list(product(lst, repeat=2)))
lst1 = [1, 2, 3]
lst2 = ['a', 'b', 'c']
print("Cartesian product of the lst1 and lst2 - ", list(product(lst1, lst2)))

Explanation

  • Line 1: We import the product function from itertools module.
  • Line 3: We define list of numbers called lst.
  • Line 4: We print the list, lst.
  • Line 5: We invoke the product function with lst and repeat=2 as arguments to obtain the cartesian product of lst with itself.
  • Line 7: We define a list of numbers, lst11.
  • Line 8: We define a list of characters, lst2.
  • Line 9: We invoke the product function with lst1 and lst2 as arguments to obtain the cartesian product between lst1 and lst2.

Free Resources