3

Why the second next doesn't return "bye" ?

def salute():
    yield "hello"
    yield "bye"


def greet_me():
    print(next(salute()))
    print(next(salute()))

greet_me()

Output :

hello

hello

1 Answer 1

6

Because you're creating a new generator each time you call salute(). Create the generator once and then call next on it to get both yields to yield their value:

def greet_me():
    gen = salute()    # create the generator
    print(next(gen))  # start it, goes to the first yield
    print(next(gen))  # resume it, goes to second yield

Calling greet_me now prints the expected results.

3
  • feel bad for asking now :(
    – Oleg
    Commented Sep 13, 2017 at 12:03
  • Never feel bad about asking a question! Commented Sep 13, 2017 at 12:11
  • 1
    @Oleg agree with Rolf, we've all been there and felt that :) Commented Sep 13, 2017 at 12:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.