While I am studying Bill Lubanovic's Introducing Python, I modified some code to understand flatten() function in chapter 9.
def flatten(lol):
for item in lol:
if isinstance(item, list):
for subitem in flatten(item):
print('yield1 ', subitem)
yield subitem
else:
print('yield2 ', item)
yield item
lol = [1, 2, [3, 4, 5], [6, [7, 8, 9],[]]]
list(flatten(lol))
I expected output is
('yield2 ', 1)
('yield2 ', 2)
('yield2 ', 3)
('yield2 ', 4)
('yield2 ', 5)
('yield1 ', 3)
('yield1 ', 4)
('yield1 ', 5)
...
...(skipped)
but the correct output of the program like this:
('yield2 ', 1)
('yield2 ', 2)
('yield2 ', 3)
('yield1 ', 3)
('yield2 ', 4)
('yield1 ', 4)
('yield2 ', 5)
('yield1 ', 5)
...
...(skipped)
I can't understand why "('yield1 ', 3)" was printed before ('yield2 ', 4), even though the loop in inner flatten() called is not over yet. I want to know if the 'yield' does stack unwinding when recursion.