Python: Passing a list through a recursive function call causes the list to become 'NoneType', why?

nonetype, python, recursion

Solution

The problem is here:

y.append(1)

The `append()` method returns `None`, so you can't pass its result for building the output list (you'd have to first `append` to the list and then pass it, as shown in other answers). Try this instead:

def recurse(y, n):
    if len(y) == n:
        return y
    else:
        return recurse(y + [1], n)

The above solution is more in line with a functional programming style. Using `append` adds an element to an existing list - which will mutate a function parameter, in general not a very good idea. On the other hand `y + [1]` creates a new list each time, leaving the parameter untouched. Proponents of functional programming will tell you that's a Good Thing.

Problem

I have the following recursive function: ``` def recurse(y,n): if len(y) == n: return y else: return recurse(y.append(1),n) ``` When I run it: ``` x=recurse([],10) ``` I get the following error: ``` TypeError: object of type 'NoneType' has no len() ``` It seems that the function gets past the if statement the 1st time around, then it goes into the next level of recursion, and there, y.append(1) is 'NoneType', why is it not: '[1]' as expected? I have thought about this for a while and I can't seem to figure it out. Any insight is appreciated!

Original source