0

Why does this

a = (i for i in range(2))
b = a
c = a
for i in b:
    print("ok")
next(c)

result in this?

StopIteration                             Traceback (most recent call last)

<ipython-input-37-9c481bb09894> in <module>()
      54 for i in b:
      55   print("ok")
 ---> 56 next(c)

StopIteration: 

I'm currently learning about generators in python. My goal here was to set up a as a generator, make b, and c instances of a and use b and c separately. What went wrong?

Additionally, everything went well when I set up something similar with a function using yield instead of the () based generator a.

  • 4
    `b` and `c` points to the same generator. You **consume** the generator with the for loop which makes it **empty**, so when asking for the next you got StopIteration error – azro Jun 21 '20 at 09:51
  • @azro Thanks, sounds plausible so far. So if I use a function with yield instead of the () it works because it calls the functions separately each time, generating independent objects, while here I only create "links" to the original object? – TheDyingOfLight Jun 21 '20 at 09:59
  • 1
    The goal is to create new instance, you don't mandatory need a `yield` https://repl.it/repls/RemoteAdventurousDemoware – azro Jun 21 '20 at 10:01
  • @azro That makes sense, thanks for your help and time. – TheDyingOfLight Jun 21 '20 at 10:05

1 Answers1

0

BOTH b and c are pointing to same generator object , while you are looping through generator b , it is consuming elements of c also , so once you consume all elements of b, and trying to consume it with c i.e by next(c) it is giving you StopIteration error.

NAGAPPA
  • 1
  • 2