Home >Backend Development >Python Tutorial >How Can I Generate All Combinations from a List of Lists in Python?
Combinations of Lists within Lists using Python
In order to obtain all combinations of elements from a list of lists, we can leverage Python's built-in itertools module. Specifically, the product function from this module offers a straightforward solution.
Using itertools.product
Consider the following example:
a = [[1,2,3],[4,5,6],[7,8,9,10]]
To generate all possible combinations of elements from these lists, we can use the following code:
import itertools combinations = list(itertools.product(*a))
The output of this code will be:
[(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), ... (3, 6, 8), (3, 6, 9), (3, 6, 10)]
The itertools.product function combines elements from the different lists in a Cartesian product manner, resulting in a list of all possible combinations. This approach is convenient and works effectively for any number of input lists.
The above is the detailed content of How Can I Generate All Combinations from a List of Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!