I've written a recursive algorithm to traverse nested iterators in Python. I don't understand why it succeeds in printing out the elements, but fails to yield them as a generator.
While I have managed to print out the elements:
tree = [[1,2],[3,[['abcde',['f']],'gh']]]
def traverse_printing(parent):
try:
for child in parent:
traverse(child)
except TypeError:
print(parent)
>>> traverse_printing(tree)
1
2
3
a
b
c
...
I am struggling to turn it into a generator.
def traverse(parent):
try:
for child in parent:
traverse(child)
except TypeError:
yield parent
traverse(tree) currently does not work. The result is:
>>> list(traverse(tree))
[]
The expected result would be [1,2,3,'a','b','c','d','e','f','g','h']
Why is it the case? Many thanks