0

I have a list of lists as such, the no. of inner list is unknown:

>>> x = [1,2,3]
>>> y = [4,5,6,7]
>>> z = [8]
>>> lol = [x,y,z]

I need to get a combinations from each item within the inner list in the order of the lol lists, I have been doing it as such to get the desired output:

>>> for i in x:
...     for j in y:
...             for k in z:
...                     print [i,j,k]
... 
[1, 4, 8]
[1, 5, 8]
[1, 6, 8]
[1, 7, 8]
[2, 4, 8]
[2, 5, 8]
[2, 6, 8]
[2, 7, 8]
[3, 4, 8]
[3, 5, 8]
[3, 6, 8]
[3, 7, 8]

What is the pythonic way to do the above? Is there a itertools function for this?

I've tried itertools.product but i didn't get the desired output:

>>> from itertools import product
>>> for i in product(lol):
...     print i
... 
([1, 2, 3],)
([4, 5, 6, 7],)
([8],)
alvas
  • 115,346
  • 109
  • 446
  • 738

3 Answers3

4

You were really close:

>>> for i in product(*lol):
...   print i
...
(1, 4, 8)
(1, 5, 8)
(1, 6, 8)
(1, 7, 8)
(2, 4, 8)
(2, 5, 8)
(2, 6, 8)
(2, 7, 8)
(3, 4, 8)
(3, 5, 8)
(3, 6, 8)
(3, 7, 8)

In the doc, there are examples like product(A, B). So you should pass every list as argument. In your case, product(x,y,z) would do the trick. The *lol notation is for unpacking.

Community
  • 1
  • 1
fredtantini
  • 15,966
  • 8
  • 49
  • 55
4

itertools.product takes a separate argument for each set, rather than a single iterable containing the sets.

for i in product(*lol):
    print i
chepner
  • 497,756
  • 71
  • 530
  • 681
0

as other answers suggest, you need to unpack lol. and as an alternative, list comprehension is more pythonic in my opinion:

import itertools


x = [1,2,3]
y = [4,5,6,7]
z = [8]
lol = [x,y,z]

print [each for each in itertools.product(*lol)] # or set()

[(1, 4, 8), (1, 5, 8), (1, 6, 8), (1, 7, 8), (2, 4, 8), (2, 5, 8), (2, 6, 8), (2, 7, 8), (3, 4, 8), (3, 5, 8), (3, 6, 8), (3, 7, 8)]
Anzel
  • 19,825
  • 5
  • 51
  • 52