Python itertools.product() Function



The Python itertools.product() function is used to compute the Cartesian product of input iterables, meaning it generates all possible combinations of elements taken from the provided iterables.

This function is useful for creating permutations, combinatorial problems, and nested loop alternatives.

Syntax

Following is the syntax of the Python itertools.product() function −

itertools.product(*iterables, repeat=1)

Parameters

This function accepts the following parameters −

  • *iterables: One or more iterables to compute the Cartesian product.
  • repeat (optional): The number of times to repeat the Cartesian product of the provided iterables (default is 1).

Return Value

This function returns an iterator that produces tuples containing all possible combinations from the input iterables.

Example 1

Following is an example of the Python itertools.product() function. Here, we compute the Cartesian product of two lists −

import itertools

list1 = [1, 2]
list2 = ['A', 'B']

result = itertools.product(list1, list2)
for item in result:
   print(item)

Following is the output of the above code −

(1, 'A')
(1, 'B')
(2, 'A')
(2, 'B')

Example 2

Here, we use the repeat parameter to generate a product of the same iterable twice −

import itertools

numbers = [0, 1]

result = itertools.product(numbers, repeat=2)
for item in result:
   print(item)

Output of the above code is as follows −

(0, 0)
(0, 1)
(1, 0)
(1, 1)

Example 3

Now, we use itertools.product() function to generate all possible meal combinations from different food categories −

import itertools

mains = ["Pizza", "Burger"]
sides = ["Fries", "Salad"]
drinks = ["Coke", "Water"]

result = itertools.product(mains, sides, drinks)
for meal in result:
   print(meal)

The result obtained is as shown below −

('Pizza', 'Fries', 'Coke')
('Pizza', 'Fries', 'Water')
('Pizza', 'Salad', 'Coke')
('Pizza', 'Salad', 'Water')
('Burger', 'Fries', 'Coke')
('Burger', 'Fries', 'Water')
('Burger', 'Salad', 'Coke')
('Burger', 'Salad', 'Water')

Example 4

When working with passwords or key combinations, the itertools.product() function can be used to generate all possible character sequences −

import itertools

characters = ['a', 'b', 'c']

result = itertools.product(characters, repeat=2)
for combination in result:
   print(''.join(combination))

The result produced is as follows −

aa
ab
ac
ba
bb
bc
ca
cb
cc
python_modules.htm
Advertisements