Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: list indices must be integers not float

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']
like image 715
Rookie Learner Avatar asked Feb 10 '26 23:02

Rookie Learner


2 Answers

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)

The for item in lst will let item get each and every item in lst on each iteration. So, change

add = int(lst[item])

to

add = int(item)

For example, try this to understand better

data = ["a", "b", "c"]
for char in data:
    print char

will print

a
b
c

If you ever wanted to get the current index of the item, then you can use enumerate function

data = ["a", "b", "c"]
for index, char in enumerate(data):
    print index, char, data[index]

Output

0 a a
1 b b
2 c c
like image 27
thefourtheye Avatar answered Feb 12 '26 16:02

thefourtheye