Trouble understanding simple example of generator

64 Views Asked by At

I found these simple examples in several places:

# a generator that yields items instead of returning a list
def firstn(n):
    num = 0
    while num < n:
        yield num
        num += 1

sum_of_first_n = sum(firstn(1000000))

def get_primes(number):
    while True:
        if is_prime(number):
            yield number
        number += 1

def solve_number_10():
    total = 2
    for next_prime in get_primes(3):
        if next_prime < 1000:
            total += next_prime
        else:
            print(total)
        return

In the first example the generator exhausts itself, in the second it doesn't but the for loop is in charge of stopping the infinite generation. A typical explanation says that yield "returns" a value, freezes the function state, and the function will continue from that state when called next(). Isn't this explanation a bit misleading? In either example I cannot "visualize" anything that calls the generator function more than once (next()). Isn't it better said that yield returns a generator, which is an iterable object that can be iterated over only once?

Edit: a generator is not an iterable object either: it generates iterable objects on the fly, and what it "yields" (not "returns") can be iterated only once. This is bit mind-bending until I can properly grasp it, like a lot of other concepts :) Thank you.

0

There are 0 best solutions below