I'm reading "Beginning python, from novice to professional", in which there is a magic flatten function which confused me.
def flatten(nested):
try:
for sublist in nested:
for element in flatten(sublist):
yield element
except TypeError:
yield nested
I know that yield returns an element. So assume I got a list L = [ 1, [[2]] ]
.
And I call it with this flatten(), like:
L = [ 1, [[2]] ]
for i in flatten(L):
print i
1
2
I was really confused, when we call the for loop, won't we triger the flatten(), and we saw the first element 1
, which no doubt will cause TypeError
in the try block, shouldn't this returned nested
variable in the except block be the whole list [1, [[2]] ]
? why would it return 1
instead?