0
votes
def hundred_numbers():
  i=0
  while i<100:
    yield i
    i=i+1

print(hundred_numbers())
g=hundred_numbers()
print(next(g))
print(next(g))
print(next(g))
print(list(h))
print(next(g))

Error:
Traceback (most recent call last): File "main.py", line 13, in print(next(g)) StopIteration

1
If you've exhausted your generator object using list, then i won't enter the loop, and won't yield anything.Chrispresso

1 Answers

1
votes

Because you've exhausted your generator object and there is nothing left for it to yield to your program.

def hundred_numbers():
    i=0
    while i<100:
        yield i
        i=i+1
g=hundred_numbers()
[next(g) for _ in range(10)] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[next(g) for _ in range(10)] # [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

See a pattern? Now let's grab the rest, i.e. 20-99

items = list(g)  # Could have done [next(g) for _ in range(20,100)]

items will now be the remaining values 20 through 99. So what happens the next time? It can't enter the while loop, so there is nothing to yield. This can be seen if you do: list(g) again. This would result in an empty list since there is nothing to grab.