Recursive functions not returning lists as expected

Paul Rudin paul.nospam at rudin.co.uk
Tue May 4 02:04:24 EDT 2010


rickhg12hs <rickhg12hs at gmail.com> writes:

> Would a kind soul explain something basic to a python noob?
>
> Why doesn't this function always return a list?
>
> def recur_trace(x,y):
>   print x,y
>   if not x:
>     return y
>   recur_trace(x[1:], y + [x[0]])
>
> Here are a couple sample runs.
>
>>>> print(recur_trace([],[1,2,3]))
> [] [1,2,3]
> [1,2,3]
>
> So that worked okay and returned the list [1,2,3].
>
>>>> print(recur_trace([9,8],[1,2,3]))
> [9,8] [1,2,3]
> [8] [1,2,3,9]
> [] [1,2,3,9,8]
> None
>
> No list is returned here.  Why?
> [Using Python 2.6.2]

Without trying it out I'd guess you want a "return" in your last
line. (If python falls out of a function without hitting an explicit
return then None is returned by default.)



More information about the Python-list mailing list