I\'m a programming newbie and am having some trouble understanding an example from my python textbook (\"Beginning Python\" by Magnus Lie Hetland). The example is for a recu
Perhaps part of your confusion is that you're thinking of the final yield statement as though it were a return statement. Indeed, a couple of people have suggested that when a TypeError is thrown in this code, the item passed is "returned". That's not the case!
Remember that any time yield appears in a function, the result is not a single item, but an iterable -- even if only one item appears in the sequence. So when you pass 1 to flatten, the result is a one-item generator. To get the item out of it, you still need to iterate over it.
Since this one-item generator is iterable, it doesn't throw a TypeError when the inner for loop tries to iterate over it; but the inner for loop only executes once. Then the outer for loop moves on to the next iterable in the nested list.
Another way to think about this would be to say that every time you pass a non-iterable value to flatten, it wraps the value in a one-item iterable and "returns" that.