How to iterate over a generator object returned by a function using `yield`?

Published on Aug. 22, 2023, 12:17 p.m.

To iterate over a generator object returned by a function using yield, you can use a loop combined with the next() function to iterate through the sequence of values generated by the generator function. Here’s an example:

def my_gen():
    yield 1
    yield 2
    yield 3

g = my_gen()  # create a generator object

for value in g:
    print(value)  # output: 1, 2, 3

# Alternatively, you can use the next() function to iterate over the generator object    
g = my_gen()
print(next(g)) # output: 1
print(next(g)) # output: 2
print(next(g)) # output: 3

In this example, my_gen() is a generator function that yield values one at a time. g is a generator object returned by calling my_gen(). You can then use a for loop to iterate over g and print out each value generated by my_gen(). Alternatively, you can use the next() function to manually iterate through the values generated by g.

Tags: