Python itertools.product Function

The itertools.product function in Python's itertools module returns the Cartesian product of input iterables. It is useful for generating all possible combinations of elements from multiple iterables.

Table of Contents

  1. Introduction
  2. itertools.product Function Syntax
  3. Examples
    • Basic Usage
    • Cartesian Product of Multiple Iterables
    • Repeating an Iterable
  4. Real-World Use Case
  5. Conclusion

Introduction

The itertools.product function creates an iterator that yields tuples representing the Cartesian product of input iterables. This means it generates all possible combinations of elements, where each combination is formed by picking one element from each iterable.

itertools.product Function Syntax

Here is how you use the itertools.product function:

import itertools

iterator = itertools.product(*iterables, repeat=1)

Parameters:

  • *iterables: One or more iterables to form the Cartesian product.
  • repeat: Optional. The number of repetitions of the product. The default is 1.

Returns:

  • An iterator that yields tuples of the Cartesian product.

Examples

Basic Usage

Generate the Cartesian product of two lists.

Example

import itertools

list1 = [1, 2]
list2 = ['a', 'b']
result = itertools.product(list1, list2)

print(list(result))

Output:

[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]

Cartesian Product of Multiple Iterables

Generate the Cartesian product of three iterables.

Example

import itertools

list1 = [1, 2]
list2 = ['a', 'b']
list3 = [True, False]
result = itertools.product(list1, list2, list3)

print(list(result))

Output:

[(1, 'a', True), (1, 'a', False), (1, 'b', True), (1, 'b', False), (2, 'a', True), (2, 'a', False), (2, 'b', True), (2, 'b', False)]

Repeating an Iterable

Generate the Cartesian product of a list with itself, repeated twice.

Example

import itertools

list1 = [1, 2]
result = itertools.product(list1, repeat=2)

print(list(result))

Output:

[(1, 1), (1, 2), (2, 1), (2, 2)]

Real-World Use Case

Generating Coordinate Grids

Use product to generate all possible coordinates in a grid.

Example

import itertools

x_coords = range(3)
y_coords = range(3)
grid = itertools.product(x_coords, y_coords)

print(list(grid))

Output:

[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

Conclusion

The itertools.product function is used for generating the Cartesian product of multiple iterables. It provides an efficient way to explore all possible combinations of elements, making it useful for various applications such as generating coordinate grids, combinatorial problems, and more.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare