0
def function():
    for i in range(5):
        yield i
        
gen = function()

print("length of gen: ", len(list(gen)))
for i in gen:
    print(i)
    assert i == 200

I don't think I understand how generators work. When I run the above code, it seems there is no iteration over gen because nothing is printing within the for loop and the assertion isn't being evaluated. How can I iterate over the generator properly?

David
  • 619
  • 2
  • 8
  • 15
  • 7
    You're entirely consuming/exhausting the generator when you do `list(gen)`, so there is nothing left to iterate over by the time you start your for-loop. – Paul M. Feb 23 '23 at 21:51
  • 1
    Why are you expecting `i == 200` to be true? – Barmar Feb 23 '23 at 21:52
  • +1 to Paul M. Either call the `function()` again to get a new generator before the for loop or calculate the length of the generator during the for loop. – njp Feb 23 '23 at 21:52
  • @Barmar I'm not. I just had that in there just to see if the for loop was executing (I put it in there before I thought about printing anything) – David Feb 23 '23 at 21:53
  • @PaulM. Oh. I know that you can iterate over a generator once, but is `list(gen)` considered iterating? – David Feb 23 '23 at 21:54
  • 2
    @David It's definitely iterating. That's what `list(...)` does - it takes an iterable to iterate over. In order to populate a list with a generator's contents, you have to iterate over it. – Paul M. Feb 23 '23 at 21:55
  • 1
    Generators are one-shot iterables. When you do `list(gen)`, it is completely exhausted. You have two choices: (1) If you're going to create a list anyway, then you can save it and then iterate over the list with your loop, e.g. do `lst = list(gen)`, then use `len(lst)` when printing the length, followed by `for i in lst:` when iterating, or (2) You can create a new generator after consuming the first, i.e. add `gen = function()` after the `print` call and before the loop. This option makes sense if rather than creating a list, you instead had two loops and didn't want to allocate a list. – Tom Karzes Feb 23 '23 at 22:06

0 Answers0