Home > Blockchain >  Python not recognizing variable as list
Python not recognizing variable as list

Time:02-17

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)

CodePudding user response:

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)

CodePudding user response:

lista[i 1] is not a list You might need: lista[i 1:]

CodePudding user response:

  • 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)
  • Related