1

I have a list of lists and need to extract each item; to ultimately write their Cartesian product.

from itertools import product

b = {}
a = [[1, 2], [3, 4], ['a', 'b']]

for i, v in enumerate(a):
  b[i] = v

#These don't work because we are feeding a single list to product
print list(product(x for x in a)) # [([1, 2],), ([3, 4],), (['a', 'b'],)]
print list(product(b.values())) # [([1, 2],), ([3, 4],), (['a', 'b'],)]

The product works correctly if I am able to get this :

print list(product([1, 2], [3, 4], ['a', 'b']))
[(1, 3, 'a'), (1, 3, 'b'), (1, 4, 'a'), (1, 4, 'b'), (2, 3, 'a'), (2, 3, 'b'), (2, 4, 'a'), (2, 4, 'b')]
Darshan Chaudhary
  • 2,093
  • 3
  • 23
  • 42

1 Answers1

1

Unpack a into itertools.product using * . Example -

print list(product(*a))

Unpacking would send each element of a as a separate argument into product , instead of a single list (just as - list(product([1, 2], [3, 4], ['a', 'b'])) ).

Demo -

>>> a = [[1, 2], [3, 4], ['a', 'b']]
>>> from itertools import product
>>> print(list(product(*a)))
[(1, 3, 'a'), (1, 3, 'b'), (1, 4, 'a'), (1, 4, 'b'), (2, 3, 'a'), (2, 3, 'b'), (2, 4, 'a'), (2, 4, 'b')]
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
  • Neat. I have seen the `*` operator many times. Does it do a similar job everywhere ? – Darshan Chaudhary Oct 06 '15 at 18:08
  • 1
    In function calls (like the above one) yes. But when you use it in function definition it is different. Then it means any amount of positional arguments (and all those positional arguments are then put into the list with the name you used after `*` ). – Anand S Kumar Oct 06 '15 at 18:09
  • Yes, there it means you wish to allow arbitrary number of arguments. Correct ? – Darshan Chaudhary Oct 06 '15 at 18:10
  • Also, I believe in Python 3.x , you have multiple unpacking assignment where `*` is used - http://stackoverflow.com/questions/2531776/multiple-unpacking-assignment-in-python-when-you-dont-know-the-sequence-length . – Anand S Kumar Oct 06 '15 at 18:10
  • Yes, you are correct. – Anand S Kumar Oct 06 '15 at 18:10