[Solved] Python: TypeError: ‘float’ object is not subscriptable

def get_data(fp):
    data = []
    for line in fp:
        line_list_ints = [int(number) for number in line.split()]
        data.append(line_list_ints)
    return data

def calculate_grades(data):
    for line in data:
        total_points = sum(line[1:6])
        grade = get_grade(total_points)
        data.insert(0,total_points)
        data.insert(1,grade)
    return data

I am getting the TypeError: ‘float’ object is not subscriptable for line 10. I do not understand why as I convert the numbers into ints before I append them into the data list. Can anyone help? Am I being clear enough?

Enquirer: ACx

||
Solution #1:

The issue is that you’re modifying the data list while you’re iterating over it, using data.insert in calculate_grades. This leads to the second iteration of the loop to see the grade value from the previous iteration as line, rather than the list of integers it is expecting.

I don’t entirely understand what you’re trying to do, so I can’t suggest a solution directly.

Perhaps you should make a separate list for the output, or modify line in place, rather than inserting a new item into data.

Respondent: Blckknght
Solution #2:

The specific problem is because there are floats in data (eventually)

for line in data:
    total_points = sum(line[1:6])
    grade = get_grade(total_points)
    data.insert(0,total_points)
    data.insert(1,grade)

Because you insert it into your list, as ‘grade’

The general problem is that you are modifying your list (‘data’) while you iterate over it, which is a bad idea – your logic will be hard to read at best, and easily loop forever.

Respondent: Cireo
Solution #3:

Uh, the issue is the part line[1:6] in line 10. The variable line is a float, so you can’t take a sublist.

Respondent: msinghal
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.