Question

so I've been trying to do this for a while now, and I can't seem to find a solution.. Maybe you could help! I'm trying to "unlist" a list of lists in order to use them in itertools.product(). as you may know, itertools.product() can recieve multiple iterables. lets say I got this list of lists:

x=[[1,2,3],["a"],["B","C"]]

if we put this into the itertools.product():

for i in product(x):
    print i

we will recieve

([1, 2, 3],)
(['a'],)
(['B', 'C'],)

What I need help with, is to find a way to "unlist" x, so there will be 3 iterables in the itertools.product(), as following:

for i in product([1,2,3],["a"],["B","C"]):
print i

which will print:

(1, 'a', 'B')
(1, 'a', 'C')
(2, 'a', 'B')
(2, 'a', 'C')
(3, 'a', 'B')
(3, 'a', 'C')
Was it helpful?

Solution

Simply use the * operator (sometimes called "splat" operator) to unpack your argument:

list(product(*x))
Out[34]: 
[(1, 'a', 'B'),
 (1, 'a', 'C'),
 (2, 'a', 'B'),
 (2, 'a', 'C'),
 (3, 'a', 'B'),
 (3, 'a', 'C')]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top