Open In App

Itertools.Product() - Python

Last Updated : 14 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The product() function from Python's built-in itertools module is a powerful tool that returns the Cartesian product of input iterables. This means it produces all possible combinations of the elements, where the result is similar to a nested for-loop. Example:

Python
from itertools import product
print(list(product([1, 2], [3, 4])))

Output
[(1, 3), (1, 4), (2, 3), (2, 4)]

Explanation: This code pairs each element of the first list with all elements of the second list, combining 1 with 3 and 4, and 2 with 3 and 4. Wrapping the product() result with list() converts the output into a list of tuples for display.

Syntax of itertools.product()

itertools.product(*iterables, repeat=1)

Parameters:

  • *iterables: One or more iterable objects (e.g., list, tuple, string).
  • repeat (Optional): The number of repetitions of the iterable. Default is 1.

Returns: It returns an iterator that yields tuples with all possible combinations, in the order of a nested loop (left to right).

Examples of itertools.product()

Example 1: In this example, we are using the repeat parameter of the product() function to generate the Cartesian product of the list [0, 1] repeated 3 times.

Python
from itertools import product
print(list(product([0, 1], repeat=3)))

Output
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

Explanation: product() with repeat=3 to generate all 3-length binary combinations from the list [0, 1]. It computes the Cartesian product [0, 1] x [0, 1] x [0, 1], resulting in tuples like (0, 0, 0) to (1, 1, 1) that represent every possible sequence of three binary digits.

Example 2: In this example, we are passing two strings ("AB" and "CD") to the product() function. Since strings are iterable in Python, each character in the string is treated as an individual element:

Python
from itertools import product
print(list(product("AB", "CD")))

Output
[('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D')]

Explanation: This code generates all possible pairs by combining each character from "AB" with each character from "CD", resulting in tuples like ('A', 'C'), ('A', 'D'), ('B', 'C') and ('B', 'D').

Example 3: In this example, we are using the product() function to compute the Cartesian product of two different lists using for loop.

Python
from itertools import product
for i in product([1, 2], ['a', 'b']):
    print(i)

Output
(1, 'a')
(1, 'b')
(2, 'a')
(2, 'b')

Explanation: This code generates all possible pairs by combining each element from the first list with each element from the second list. The for loop iterates through these pairs and prints them, resulting in the tuples (1, 'a'), (1, 'b'), (2, 'a') and (2, 'b').


Next Article
Article Tags :
Practice Tags :

Similar Reads