Error: list indices must be integers not float

python, python-2.7

Solution

The issue is on this line:

for item in lst:
    add = int(lst[item])

`for item in lst` Iterates through each `item` in the list, not an index. So `item` is the value of the float in the list. Instead try this:

for item in lst:
    add = int(item)

Additionally, there is no reason to cast to an integer as this will mess with your average, so you can shorten it further to:

for item in lst:
    add = item

Which means the for loop can be shortened to just:

for item in lst:
    total+= item

Which means we can shorten it even further, using the `sum` built in:

total = sum(lst)

Since `total` is now a float, we don't need to specify float division using the double slash, and we no longer need to cast the length to a float, so the function becomes:

def average(lst):
    l=len(lst)
    total = sum(lst)
    return total/l

And lastly, there is no reason to not do this all on one easy to read line:

def average(lst):
    return sum(lst)/len(lst)

Problem

The code following should take the list of marks from the dictionary of a student and calculate the average marks of the student. I am getting the "TypeError: list indices must be integers, not float" error. ``` alice = { "name": "Alice", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0] } # Averege function is given below for calculating avg def average(lst): l=float(len(lst)) total = 0.0 #code works till here the error occoured below for item in lst: add = int(lst[item]) print add total+=add return total//l print average(alice['tests']) print alice['tests'] ```

Original source