1
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?

3
  • 1
    Why are you slicing from 1 to 6 on line? Commented Mar 24, 2015 at 0:49
  • I need to add just the numbers in spots [1:6] from each line Commented Mar 24, 2015 at 0:56
  • how do I do a full traceback? Commented Mar 24, 2015 at 1:01

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

See also - what Blckknght said
0

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.

3 Comments

I'm not sure why line is a float. It depends on the value of the parameter data that you pass to calculate_grade. It's probably a list of floats, and since line is an element of data, it is also a float.
Can you post the full code, so I can see the code that calls calculate_grades?
fp = open("data.short.txt") data = get_data(fp) grades = calculate_grades(data)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.