Understanding how is a function evaluated using recursion

Terry Reedy tjreedy at udel.edu
Wed Sep 25 21:12:02 EDT 2013


On 9/25/2013 7:24 PM, 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?

It is not clear what part of 'how' you do not understand this. Perhaps 
that fact that a new execution frame with a new set of locals is created 
for each call.  So calling flatten from flatten is no different than 
call flatten from anywhere else.

If a language creates just one execution frame for the function, 
attached to the function (as with original Fortran, for instance), then 
recursion is not allowed as a 2nd call would interfere with the use of 
the locals by the 1st call, etc.

-- 
Terry Jan Reedy




More information about the Python-list mailing list