简体   繁体   中英

Python strange yield behavior in recursive function

This is just a demo code to understand the yield behavior in a recursive function. I expect it to return an iterable list [5,4,3] but it stops at the first iteration and only returns [5]

Can anyone explain why this happens?

def yield_test(input):
    if input > 3:
        yield_test(input-1)

    yield input

print(list(yield_test(5)))

output: [5] Expected output: [5, 4, 3]

You need to yield from yield_test() and reverse the order of yield s in your function:

def yield_test(input):
    yield input

    if input > 3:
        yield from yield_test(input-1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM