I am wondering why list(prod)
is an empty list? But a print it out the print(type(list(prod)))
is an list and print(list(prod))
did show a list with 64 tuples.
from itertools import product
a = [1, 2]
b = [3,4]
c = [5,6]
prod = product(a, b, c,repeat=2) #
print(list(prod))
print(type(list(prod)))
mylist = list(prod)
print(mylist)
y = 0
for i in mylist:
print(i)
y = 1
print(y)
CodePudding user response:
The return value of product
is a generator, and it gets exhausted once its been iterated upon. The first time this generator is iterated when you are calling print(list(prod))
and then when you again try to call print(type(list(prod)))
there is no entity left in the iterator. A better approach would be:
from itertools import product
a = [1, 2]
b = [3, 4]
c = [5, 6]
prod = product(a, b, c,repeat=2)
prod_list = list(prod) # Generator exhausted only once.
print(prod_list)
print(type(prod_list))
# Make any amount of calls to prod_list