Home >Backend Development >Python Tutorial >How can I generate all combinations of elements from a list of lists in Python?

How can I generate all combinations of elements from a list of lists in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-02 16:54:11458browse

How can I generate all combinations of elements from a list of lists in Python?

Generating All Combinations of a List of Lists

When dealing with nested data structures, it becomes essential to manipulate them efficiently. One common task is to retrieve all possible combinations of elements across multiple lists.

For Python developers, the itertools.product function provides a concise and elegant solution to this problem. It takes multiple iterables as arguments and generates tuples representing all possible combinations of elements from each iterable.

Answer:

To generate all combinations of elements in a list of lists, use itertools.product as follows:

import itertools

my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]

result = list(itertools.product(*my_list))

This will produce a list of tuples, each representing a unique combination of elements from the input lists.

Example Output:

[(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 4, 10), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 5, 10),
(1, 6, 7), (1, 6, 8), (1, 6, 9), (1, 6, 10), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 4, 10),
(2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 5, 10), (2, 6, 7), (2, 6, 8), (2, 6, 9), (2, 6, 10),
(3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 4, 10), (3, 5, 7), (3, 5, 8), (3, 5, 9), (3, 5, 10),
(3, 6, 7), (3, 6, 8), (3, 6, 9), (3, 6, 10)]

Using itertools.product is a convenient and efficient way to generate all possible combinations of elements from complex data structures in Python.

The above is the detailed content of How can I generate all combinations of elements from a list of lists in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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