Why this code throws "StopIteration":
stub_generator = (x for x in range(5))
stub_dict = {}
stub_dict[next(stub_generator)] = list(stub_generator)
and this works?
stub_generator = (x for x in range(5))
stub_dict = {}
temp_1 = next(stub_generator)
temp_2 = list(stub_generator)
stub_dict[temp_1] = temp_2
This behavior is because of two things:
The right-hand side of an assignment statement is evaluated before the left-hand side.
Generator objects can be iterated over only once.
To explain further, when this code is executed:
stub_dict[next(stub_generator)] = list(stub_generator)
this part:
list(stub_generator)
will be evaluated before this part:
stub_dict[next(stub_generator)]
Moreover, placing stub_generator in list will cause the generator to be iterated over entirely and thus exhausted. When next(stub_generator) is then evaluated afterwards, a StopIteration exception is raised because stub_generator is now empty.
This code however is different:
temp_1 = next(stub_generator)
temp_2 = list(stub_generator)
It will execute next(stub_generator) before executing list(stub_generator). Meaning, stub_generator will still have some items in it when it is converted to a list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With