+ 3

Function returns a list in Python

Hi everyone! I'm new in Python, i'm trying to create a function that return a list and this is my code: def fi(n): list1=[] for i in range (n+1): if i==0 or i==1: a=1 if i>1: a[i]=a[i-1]+a[i-2] list1=list1.append(a) return list1 fi(5) But when i run it, it returns error "'NoneType' object has no attribute 'append'". Why i got this error while i created a variable list1 that's a list? Thanks everyone!

20th Sep 2019, 8:57 AM
Tiktok
6 ответов
+ 5
hi there are aome issues in your code: def fi(n): list1=[] for i in range (n+1): if i==0 or i==1: a=1 if i>1: #a[i]=a[i-1]+a[i-2] # you have to rework this ***1 a =99 list1.append(a) # <-changed!! return list1 fi(5) #***2 use: result = fi(5) ***1 you have an integer var "a" and you try to to use an index on it. this is not possible => if you can explain what you ar trying to do here, i cold help you. ***2 you should use a call like this, otherwise you could not catch the returned list
20th Sep 2019, 9:12 AM
Lothar
Lothar - avatar
+ 4
append() does add the element to the list but does not have a return value (it returns None). So you don't need to reassign it to the list1 variable. Just change that line to this: list1.append(a) And it should work
20th Sep 2019, 9:07 AM
Tibor Santa
Tibor Santa - avatar
+ 4
Catalin, the reason why the expression <a[i]=a[i-1]+a[i-2]> does not create an error (at this time) is the behaviour of the interpreter, which doesn't execute this line of code because of var i is not greater than 1. So the first error in the logical flow of code sequence is <list1=list1.append(a)>. (This should be: <list1.append(a)>) You can trace this in debug mode. If you change condition from <if i >1:> (temporarily) to <if True:> the interpreter will try to execute expression <a[i]=a[i-1]+a[i-2]> which leads to an error like <int object is not subscriptable...> In compiler languages this will not happen, because types will be checked all in advance (except user does input an unproper value at runtime.
22nd Sep 2019, 7:33 AM
Lothar
Lothar - avatar
+ 2
Thanks very much,i understand the reason and i'm working on it!! i'm trying to create a list of Fibonacci Sequence
20th Sep 2019, 9:25 AM
Tiktok
+ 2
ok, just to give you something that is essy to understand: def fi(n): list1=[0, 1] # this has to be pre-set for i in range (n-2): list1.append(list1[-1]+list1[-2]) # -1 is the last element, -2 the penultimate element in list1 return list1 print(fi(10))
20th Sep 2019, 11:51 AM
Lothar
Lothar - avatar
0
Oh indeed i did not saw that method call fi(5). I was assuming that the iteration starts with i = 1
5th Dec 2019, 9:46 PM
Catalin Popinciuc
Catalin Popinciuc - avatar