简体   繁体   中英

Python recursion return None on list

Hi I am trying to practice on recursion question and have been facing an issue

def recurr(container = [], index = 0):
    print(str(container) + " " + str(index))
    if index == 10:
        return recurr

    recurr(container.append(index), index+1)

print(recurr())

This function takes container as list and index as int, now I am trying to append index in container and increment index. But whenever the function is called the value of the container becomes 'None' and I get an error "AttributeError: 'NoneType' object has no attribute 'append'". I am not sure what am I doing wrong so if someone can help me understand that I would be really grateful.

Thank you

What Tom Karzes mentioned above is correct. There are a few issues

  1. container.append(index) does not return the container itself. The .append() method appends an item to a container, but does it in place. You need to pull that command up a line, and then pass the container to recurr() .

  2. The issue with the default argument being an empty list is also a valid point but probably beyond the scope of this discussion. Just pass in a list explicitly

  3. Your return statement is returning the function when it should probably be returning the container.

  4. The last line needs to return function call return recurr(container, index+1) . Without it, you will get all the print statements but the final return value will STILL be None. To understand why, you need to understand a bit about stack frames and function call frames. Each function is calling itself, and when it does, a new stack frame is added, the calling frame can only exit when all downstream frames exit. When the final frame exits, it returns the full container, but it returns it to its caller, which is recurr(container, 9) . Of course, if you look at the function, there are NO other return statements, so that frame returns None, and each subsequent frame continues to return None.

Try this:

def recurr(container, index = 0):
    print(str(container) + " " + str(index))
    if index == 10:
        return container
    
    container.append(index)
    return recurr(container, index+1)

x = []
print(recurr(x))

This can be tricky to fully understand so please ask questions and do a little experimentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM