简体   繁体   中英

How to create an integer array within a recursion?

The following code tries to create an integer array filled with n times number 1.

import sys

def foo(n):
    if n == 0:
        return []
    else:
        return foo(n-1).append(1)

if __name__ == '__main__':
    foo(5)

Executing this program yields in an error:

AttributeError: 'NoneType' object has no attribute 'append'

What am I doing wrong when creating the array?

The problem is in your else -clause. append does not return a new list, but rather adds an element to the list in-place, and then returns None (hence your error). Try this instead,

return foo(n-1) + [1]  # creates a *new* list

Just look at the following code to understand why you are getting the error,

>>> x = [].append(1)
>>> x is None
True

When you append to a list, the return value is None ! So you must do something like this,

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

Using + operator is really like calling extend on a list for which the return value is the new list , unlike append .

>>> x = [1] + [1]
>>> x
[1, 1]

NOTE: Obviously for this simple example you should just use,

>>> [1] * 6
[1, 1, 1, 1, 1, 1]

Which is fine for immutable int s but if you are dealing with objects where you don't want references to the same one,

>>> [1 for _ in range(6)]
[1, 1, 1, 1, 1, 1]

But I'm assuming you are writing this to practice recursive solutions and such.

it might be worth noting that python has some nice syntax to cover your usecase:

>>> [1]*5
[1, 1, 1, 1, 1]

Your program, slightly changed

import sys

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

if __name__ == '__main__':
    print(foo(5))

Prints

[1, 1, 1, 1, 1]

list.append() modifies the list, but doesn't return anything. So recursions of your function that reach that branch actually return nothing or None .

The method I listed appends an element to the list, and then returns the list, so your recursion works just as you had wanted.

append returns None . This is the problem.

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