Search code examples
pythonpython-3.xwhile-loopgeneratoryield

Python generators and yield - increment to the next() call in a while loop


In the code snippet below, how would you increment the next() call using an operator += instead of typing print(next(seq)) four times? With this in a while loop, only the first instance of print(next(seq)) will print repeatedly. How do I advance to the next one with each iteration?

def get_sequence_upto(x):
    for i in range(x):
        yield i 

seq = get_sequence_upto(5)

print(next(seq))

print(next(seq))

print(next(seq))

print(next(seq))

Output:

0
1
2
3

edit: added the while loop snippet

while True:
seq = loop_here(x)

        print(next(seq))

I have tried adding += to different points within the code with no success.


Solution

  • Use yield from with a for loop:

    def get_sequence_upto(x):
        yield from range(x)
    
    nums = get_sequence_upto(5)
    while True:
        x = next(nums, None)
        if x is not None:
            print(x)
            continue
        break
    

    Or with try except:

    def get_sequence_upto(x):
        yield from range(x)
    
    nums = get_sequence_upto(5)
    while True:
        try:
            print(next(nums))
        except StopIteration:
            break