Understanding how is a function evaluated using recursion

MRAB python at mrabarnett.plus.com
Wed Sep 25 20:07:01 EDT 2013


On 26/09/2013 00:24, Arturo B wrote:
> Hi, I'm doing Python exercises and I need to write a function to flat nested lists
> as this one:
>
> [[1,2,3],4,5,[6,[7,8]]]
>
> To the result:
>
> [1,2,3,4,5,6,7,8]
>
> So I searched for example code and I found this one that uses recursion (that I don't understand):
>
> def flatten(l):
>      ret = []
>      for i in l:
>          if isinstance(i, list) or isinstance(i, tuple):
>              ret.extend(flatten(i)) #How is flatten(i) evaluated?
>          else:
>              ret.append(i)
>      return ret
>
> So I know what recursion is, but I don't know how is
>
>                         flatten(i)
>
> evaluated, what value does it returns?
>
Try a simpler version first:

def flatten(l):
     ret = []
     for i in l:
         if isinstance(i, list) or isinstance(i, tuple):
             # Append the contents of the item.
             ret.extend(i)
         else:
             # Append the item itself.
             ret.append(i)
     return ret

In this example, flatten([[1,2,3],4,5,[6,[7,8]]]) returns [1,2,3,4,5,6,
[7,8]].

The problem here is that a sublist can itself contain a list.

It would be nice if there were a function which, when given [6,[7,8]],
would return [6,7,8] so that you could append those items.

But that's exactly what flatten does!

Try adding prints to tell you what was passed in and what is returned.




More information about the Python-list mailing list