Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning generator to dictionary directly throws StopIteration

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
like image 622
x3al Avatar asked Feb 03 '26 07:02

x3al


1 Answers

This behavior is because of two things:

  1. The right-hand side of an assignment statement is evaluated before the left-hand side.

  2. 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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!