Home > Backend Development > Python Tutorial > How Can itertools.product Generate the Cartesian Product of Multiple Lists in Python?

How Can itertools.product Generate the Cartesian Product of Multiple Lists in Python?

Susan Sarandon
Release: 2025-01-04 12:23:38
Original
329 people have browsed it

How Can itertools.product Generate the Cartesian Product of Multiple Lists in Python?

Cartesian Product of Multiple Lists with itertools.product

To obtain the Cartesian product of a group of lists, where every possible combination of values is generated, utilize the built-in itertools.product function. This feature has been included in Python since version 2.6.

Implementation:

import itertools

somelists = [
   [1, 2, 3],
   ['a', 'b'],
   [4, 5]
]

for element in itertools.product(*somelists):
    print(element)
Copy after login

Alternatively, you can provide separate arguments to the function like this:

for element in itertools.product([1, 2, 3], ['a', 'b'], [4, 5]):
    print(element)
Copy after login

Either approach will generate the same output:

(1, 'a', 4)
(1, 'a', 5)
(1, 'b', 4)
(1, 'b', 5)
(2, 'a', 4)
(2, 'a', 5)
...
Copy after login

Note:

  • This technique is commonly employed to avoid deeply nested loops.
  • If you need the Cartesian product of the same list multiplied by itself, consider using itertools.product with arguments unpacked with *.
  • The use of * to unpack arguments in this context is not different from its typical usage in function calls.

The above is the detailed content of How Can itertools.product Generate the Cartesian Product of Multiple Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template