sixtytrees sixtytrees - 2 months ago 13
Python Question

Turn a list into a tuple of arguments

Python

itertools.product()
takes coma separated 1D lists and returns a product. I have a list of divisors of a number in a form

l=[[1, a1**1,a1**2,..a1**b1],[1,a2**1,..a2**b2],..[1, an**1, an**2,..an**bn]]


When I pass it to itertools.product() as an argument I don't get the desired result. How can I feed this list of lists of integers to product()?

import itertools

print([list(x) for x in itertools.product([1,2,4],[1,3])])
# [[1, 1], [1, 3], [2, 1], [2, 3], [4, 1], [4, 3]] #desired

l1=[1,2,4],[1,3] #doesn't work
print([list(x) for x in itertools.product(l1)])
#[[[1, 2, 4]], [[1, 3]]]

l2=[[1,2,4],[1,3]] #doesn't work
print([list(x) for x in itertools.product(l2)])
#[[[1, 2, 4]], [[1, 3]]]

Answer

You need to use *l2 within the product() as * unwraps the list. In this case, the value of *[[1,2,4],[1,3]] will be [1,2,4],[1,3]. Here's your code:

l2 = [[1,2,4],[1,3]] 
print([list(x) for x in itertools.product(*l2)])
# Output: [[1, 1], [1, 3], [2, 1], [2, 3], [4, 1], [4, 3]]

Please check: What does asterisk mean in python. Also read regarding *args and **kwargs, you might find it useful. Check: *args and **kwargs in python explained