Understanding how is a function evaluated using recursion

Dave Angel davea at davea.name
Wed Sep 25 20:26:23 EDT 2013


On 25/9/2013 19: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:

I can't imagine why you'd use either i or l in this context, but
especially use them both when they look so much alike.

>         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?
>

flatten() returns a list, of course.  The value of 'ret' in the inner
function.

What don't you understand about recursion?  You write a function that's
valid for the simple case (a simple list, with none of the elements
being lists or tuples).  Then you use that function inside itself to
handle the more complex cases.


-- 
DaveA





More information about the Python-list mailing list