Reputation: 1219
As a Python newbie, it might be a silly question, but I can't find a solution. I'm doing the product of a tuple, and working perfectly, like this:
list = list(itertools.product(["this", "the"],["example", "test"],["is not", "isnt"],[" working", "correct"]))
print(list)
But if a declare another variable, it does not work anymore:
test = ["this", "the"],["example", "test"],["is not", "isnt"],[" working", "correct"]
list = list(itertools.product(test))
print(list)
I checked with the type()
function to get the class, and it's a tuple...
I'm running this in Python 3.x but I would like to make it compatible for 2.7
Upvotes: 0
Views: 1245
Reputation: 60070
First off, it's bad to use list
as a variable name, since this overwrites the default list
function.
In your first, working, example, you pass multiple arguments to itertools.product
, and it combines each argument to give the output you want. In your nonworking example, you only pass a single argument, the tuple test
. Thankfully you can use Python's tuple unpacking syntax to expand each element of the tuple into an argument:
test = ["this", "the"],["example", "test"],["is not", "isnt"],[" working", "correct"]
# The * before test unpacks the tuple into separate arguments
result2 = list(itertools.product(*test))
print(result2)
[('this', 'example', 'is not', ' working'), ('this', 'example', 'is not', 'correct'), ('this', 'example', 'isnt', ' working'), ('this', 'example', 'isnt', 'correct'), ('this', 'test', 'is not', ' working'), ('this', 'test', 'is not', 'correct'), ('this', 'test', 'isnt', ' working'), ('this', 'test', 'isnt', 'correct'), ('the', 'example', 'is not', ' working'), ('the', 'example', 'is not', 'correct'), ('the', 'example', 'isnt', ' working'), ('the', 'example', 'isnt', 'correct'), ('the', 'test', 'is not', ' working'), ('the', 'test', 'is not', 'correct'), ('the', 'test', 'isnt', ' working'), ('the', 'test', 'isnt', 'correct')]
Upvotes: 2