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

StackOverflow https://stackoverflow.com/questions/21792571

  •  12-10-2022
  •  | 
  •  

Question

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!

Was it helpful?

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.

OTHER TIPS

list.append() calls the append method on a list, and while it modifies the list, it returns None.

So it does not return the list.

You want something like:

def recurse(y,n):
    if len(y) == n:
        return y
    else:
        y.append(1)
        return recurse(y,n) # explicitly pass the list itself

y.append operates on y in place and returns None

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top