Why is this python generator returning the same value everytime?
问题 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]] ? 回答1: 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: >>> r = list(gen()) >>> r [[4], [4], [4], [4]