I have this generator that yields lists:
def gen():
state = [None]
for i in range(5):
state[0] = i
yield state
And here's the output, when I call it:
>>> list(gen())
[[4], [4], [4], [4], [4]]
Why are all the elements [4]
? Shouldn't it be [[0], [1], [2], [3], [4]]
?
You are reusing the same list object. Your generator returns the one object over and over again, manipulating it as it goes, but any other references to it see those same changes:
Yield a copy of the list or create a new fresh list object instead of manipulating one.
You are
yielding
the samelist/object
so you always see the last values added to the list. You should yield a copy:Or create the list inside the first loop:
It would be as easy to create a new list/object each time: