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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With