Reputation: 43
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]
Upvotes: 0
Views: 46
Reputation: 36765
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)
Upvotes: 2