Written by
Matthew Bilyeu
on
on
Constructing a list from an iterable in Python
I discovered this unexpected behavior in Python when a generator function yields an (object) element, mutates that object, and yields it again. Iterating over the result of the generator has a different effect than constructing a list from that iterable:
>>> def gen_stuff(): ... output = {} ... yield output ... output['abc'] = 123 ... yield output ... >>> yielded = gen_stuff() >>> for y in yielded: print(y) ... {} {'abc': 123} >>> yielded = gen_stuff() >>> list(yielded) [{'abc': 123}, {'abc': 123}]
Not sure what’s going on here…