Help- Simple recursive function to build a list - Sorry for all the noise!

actuary77 actuary77 at elemental-systems.com
Wed Mar 2 00:03:01 EST 2005


actuary77 wrote:
> I am trying to write simple recursive function to build a list:
> 
> 
> def rec(n,alist=[]):
>     _nl=alist[:]
>     print n,_nl
>     if n == 0:
>         print n,_nl
>         return _nl
>     else:
>         _nl=_nl+[n]
>         rec(n-1,_nl)
> 
> _nl=[]
> _nl=rec(4)
> print _nl
> 
> ### shouldn't this work?
> 
> _nl=rec(4)
> 
> 
> 
> 
> The output is:
> 4 []
> 3 [4]
> 2 [4, 3]
> 1 [4, 3, 2]
> 0 [4, 3, 2, 1]
> 0 [4, 3, 2, 1]
> None
> None
> 
> 
> Question:
> ============
> Why isn't the function returning a list?
> Why is function returning None?
> 
> Any guidance from one of you pro's would be greatly appreciated.
> 
> Thanks,
> DKoch
> actuary77 at elemental-systems.com
Sorry for all of the noise!

It now makes sense if I write it, (simple):

def rec2(n):
     if n == 0:
         return []
     else:
         return [n] + rec2(n-1)

print rec2(4)
   => [4,2,3,1]

Thank you for the help!






More information about the Python-list mailing list