Reputation: 41
def upto(n):
items = []
for i in range(n):
items.append(i)
yield items
print(list(upto(2)))
Why is the print output [[0,1],[0,1]]
? When I call next on upto(2) twice, it yields [0]
the first time and [0,1]
the second time, so shouldn't the result be [[0], [0,1]]
?
Upvotes: 4
Views: 80
Reputation: 71
The thing is,you are referencing the same list(list work by reference) when trying to call list method on a generator. the list you are yielding is updated each time you loop through.so when you list up the generator it gets the updated one. for getting what you want you could do one of the following two things,
yield items[:]
for i in upto(2):
print(i) # here,each time it gets the current one
Upvotes: 0
Reputation: 646
In [1]:
def upto(n):
items = []
for i in range(n):
items.append(i)
yield items.copy()
list(upto(2))
Out[1]: [[0], [0, 1]]
Upvotes: 0