ilmoi
ilmoi

Reputation: 2534

python: why do I need to assign a generator function to a variable or it won't work?

Why does this work:

def even_gen():
    n = 0
    while True:
        yield n
        n += 2

evens_ = even_gen()
evens = list(next(evens_) for _ in range(5))

#[0,2,4,6,8]

But this doesn't:

def even_gen():
    n = 0
    while True:
        yield n
        n += 2

evens = list(next(evens_gen()) for _ in range(5))

#[0,0,0,0,0]

The only difference is moving the generator inside the list function. I find it super peculiar that we need to first assign it to a variable, and then it works...

What's the reason?

Upvotes: 1

Views: 512

Answers (1)

DeepSpace
DeepSpace

Reputation: 81594

Because evens_gen() creates a new generator in every iteration hence next will always get the first element which is 0.

Upvotes: 6

Related Questions