Combinations from list of lists

I want to get all the possible combinations like so:

a = [1, 2, 3]
b = [4, 5]
c = [-1]

print(list(product(a, b, c)))

Output:

[(1, 4, -1), (1, 5, -1), (2, 4, -1), (2, 5, -1), (3, 4, -1), (3, 5, -1)]

However, I have all my lists stored inside a list:

s = [[1,2,3], [4,5], [-1]]

print(list(product(s)))

Output:

[([1, 2, 3],), ([4, 5],), ([-1],)]

I’ve previously tried unpacking the list, but I’ve only been able to create one big list, or a dictionary. Is there another way of unpacking the list or getting the product in the same way as the first example?

>Solution :

This is argument unpacking, demonstsrated in the tutorial at 4.8.5. Unpacking Argument Lists:

>>> print(list(product(*s)))
[(1, 4, -1), (1, 5, -1), (2, 4, -1), (2, 5, -1), (3, 4, -1), (3, 5, -1)]

Leave a Reply