Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>yield element</code> can be executed if <code>nested</code> is a list but <code>sublist</code> is not (i.e., if <code>nested</code> is a normal "flat" list). In this case, <code>for sublist in nested</code> will work fine. When the next line recursively calls <code>flatten sublist</code> a typerror will be raised when the recursive call tries to iterate over the "sublist" (which is not iterable). This TypeError is caught and the recursive call yields the <em>entire input list</em> back, so it is then iterated over by the <code>for element in flatten(sublist)</code> call. In other words, <code>for element in flatten(sublist)</code> winds up doing <code>for element in sublist</code> if sublist is already flat.</p> <p>The key thing to recognize is that even a non-nested list will result in a recursive call. A call like <code>flatten([1])</code> will result in <em>two</em> yields: the recursive call will yield <code>[1]</code> to the outer call, and the outer call immediately re-yields <code>1</code>.</p> <p>This version of the function may help to understand what's going on:</p> <pre><code> def flatten(nested, indent=""): try: print indent, "Going to iterate over", nested for sublist in nested: print indent, "Going to iterate over flattening of", sublist for element in flatten(sublist, indent+" "): print indent, "Yielding", element yield element except TypeError: print indent, "Type Error! Yielding", nested yield nested &gt;&gt;&gt; list(flatten([[1,2],3])) Going to iterate over [[1, 2], 3] Going to iterate over flattening of [1, 2] Going to iterate over [1, 2] Going to iterate over flattening of 1 Going to iterate over 1 Type Error! Yielding 1 Yielding 1 Yielding 1 Going to iterate over flattening of 2 Going to iterate over 2 Type Error! Yielding 2 Yielding 2 Yielding 2 Going to iterate over flattening of 3 Going to iterate over 3 Type Error! Yielding 3 Yielding 3 [1, 2, 3] </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload