-1

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?

Gonde94
  • 57
  • 8
  • 2
    Unpacking `s` gives the exact result you want. What do you mean "I've previously tried unpacking the list, but ..."? – Pranav Hosangadi Mar 03 '23 at 17:34
  • Apologies for being unclear. By unpacking, I mean all the solutions I found online took the elements out of their individual lists and created one big list, i,e, s = [1, 2, 3, 4, 5, -1], which is not what I wanted to do. Wim's solution worked for me. – Gonde94 Mar 03 '23 at 17:44
  • Duplicate: https://stackoverflow.com/questions/3034014/how-to-apply-itertools-product-to-elements-of-a-list-of-lists – Pranav Hosangadi Mar 03 '23 at 20:22

2 Answers2

2

This is argument unpacking, demonstrated 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)]
wim
  • 338,267
  • 99
  • 616
  • 750
  • 2
    Then they probably didn't try unpacking *correctly*. – chepner Mar 03 '23 at 17:35
  • @PranavHosangadi We don't know how they attempted to do so (not shown), or if they even know what that term actually means in context. This gets the desired output. – CrazyChucky Mar 03 '23 at 17:36
0

You can use *

from itertools import product

s = [[1,2,3], [4,5], [-1]]
result = list(product(*s))
print(result)
Abdulmajeed
  • 1,502
  • 2
  • 10
  • 13