I am playing around a bit with generators in Python, and am trying to make use of a simple recursive scheme to implement a flatten-function. That is, a function that takes as input a list that may contain sublists, and outputs a iterable objects that iterates only over the atomic elements of the input.
So, print(list(flatten([1,2,3,[4,5,6]])))
should return something containing [1,2,3,4,5,6]
.
My attempt is as follows:
def flatten(toflatten):
try:
for element in toflatten:
flatten(element)
except TypeError:
yield toflatten
So, it should check whether its argument is an iterable object. If this is the case, also recurse over this object. Else, yield it as an atomic element.
This does not work and flatten([1,2,3,[4,5,6]])
merely returns an empty list.
Why is this the case? And in particular; why is it not even performing the recursive function calls on this input? (I am using Python 3.5)