Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python itertools.product() Function



The Pythonitertools.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 itertoolslist1 = [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 therepeat parameter to generate a product of the same iterable twice −

import itertoolsnumbers = [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 itertoolsmains = ["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 itertoolscharacters = ['a', 'b', 'c']result = itertools.product(characters, repeat=2)for combination in result:   print(''.join(combination))

The result produced is as follows −

aaabacbabbbccacbcc
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp