user2331057
user2331057

Reputation: 23

Python itertools.product with arbitrary number of sets

I wish to execute the following code:

temp = []
temp.append([1,2])
temp.append([3,4])
temp.append([5,6])

print list(itertools.product(temp[0],temp[1],temp[2]))

However, I would like to execute it for temp with arbitrary length. I.e. something more like:

print list(itertools.product(temp))

How do I format the input correctly for itertools.product to produce the same result in the first segment of code without explicitly knowing how many entries there are in temp?

Upvotes: 2

Views: 738

Answers (2)

Dragos Alexe
Dragos Alexe

Reputation: 131

Or can do that:

Combine lists using zip. The result is a list itertator.

a = ["A", "a"]
b = ["B", "b"]
c = ["C", "c"]

number_iterator = zip(a,b,c)
numbers = list(number_iterator)

print (numbers)

Upvotes: 0

user2357112
user2357112

Reputation: 280837

print list(itertools.product(*temp))

Use * to unpack the argument iterable as separate positional arguments.

Upvotes: 3

Related Questions