Home > Back-end >  why I cannot append a number to a list in python
why I cannot append a number to a list in python

Time:01-31

I tried to append a number to the fib_list in the else block below, but got an error saying "unsupported operand type(s) for : 'int' and 'list'". Based on my understanding the result of fib(n-2) fib(n-1) should be a number, but why I got the type error?

enter image description here

CodePudding user response:

You have 3 return statement, in two you return an int:

if n == 0:
    return 0
if n == 1:
    return 1

in one you return a list:

fib_list.append(fib(n-2)   fib(n-1))
return fib_list

so in the addition you get the TypeError.


You can try to write the function in different mode, if you like to track the Fibonacci sequence into a list you can store the addition result, append to list and return it for instance.

num = fib(n-2)   fib(n-1)
fib_list.append(num)
return num

CodePudding user response:

I tried this and it worked (identical to your code), what version of python do you have installed?

fib_list = []
def fib(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    else:
        fib_list.append(fib(n-1)   fib(n-1))
        return fib_list
    
print(fib(3))

The output when i ran it was [2, 2, [2, 2, 2, 2]], so maybe you're having issues appending a list to another list.

  •  Tags:  
  • Related