'Python not recognizing variable as list
My function receives a LIST but I am getting
TypeError: object of type 'int' has no len()
def sum_list(lista):
last = len(lista)
for i in range(last):
return lista[i] + sum_list(lista[i+1])
lista = [1, 5, 3, 4, 2, 0]
sum_list(lista)
Solution 1:[1]
lista[i+1] is an int and you pass that to your function :) hence the error
Edit: also there is a python built-in sum (if you just need the sum of a list)
my_list = [42, 0, 41, 74]
list_sum = sum(my_list)
Solution 2:[2]
lista[i+1] is not a list
You might need: lista[i+1:]
Solution 3:[3]
- You didn't call the function with the list in line 4
- You need to give a return 0 finally else it will throw an error int + None not supported
The Corrected Code:
def sum_list(lista):
last = len(lista)
for i in range(last):
return lista[i] + sum_list(lista[i+1:])
return 0
lista = [1, 5, 3, 4, 2, 0]
sum_list(lista)
Another easy to understand version:
def sum_list(lista):
sum = 0
for i in lista:
sum += i
return sum
lista = [1, 5, 3, 4, 2, 0]
sum_list(lista)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | IceTDrinker |
| Solution 2 | PySoL |
| Solution 3 | Lamin Muhammed |
