Alan Robinson
Alan Robinson

Reputation: 69

Adding lists in 2D lists

marks = [[12,14,8,7,17],[6,8,5,3,13],[16,15,9,10,18]]

total = 0
for s in range(3):
    for m in range(5):
        total[s] = total[s] + marks [s][m]
        print("total for student",s,"is",total[s])

Why does this throw the error below?

TypeError: 'int' object is not subscriptable

Upvotes: 1

Views: 51

Answers (2)

Mauro Baraldi
Mauro Baraldi

Reputation: 6575

You do not need indeed to know the length of your list, if you will run through it. If you are doing it for indexing, use enumerate instead.

And, as The6thSense said, use sum for calculate each student's list

Tip: Use of format makes your code more elegant! :-)

marks = [[12,14,8,7,17],[6,8,5,3,13],[16,15,9,10,18]]

for index, student in enumerate(marks):
    print('Total for student {student} is {total}'.format(student=i, total=sum(j)))

Total for student 0 is 58
Total for student 1 is 35
Total for student 2 is 68

Upvotes: 0

The6thSense
The6thSense

Reputation: 8335

We could simplify your code and make it work

Code:

marks = [[12,14,8,7,17],[6,8,5,3,13],[16,15,9,10,18]]    
total = 0
for s in range(len(marks)):
    print("total for student",s,"is",sum(marks[s]))

Output:

total for student 0 is 58
total for student 1 is 35
total for student 2 is 68

Making changes to your code

Code1:

marks = [[12,14,8,7,17],[6,8,5,3,13],[16,15,9,10,18]]


for s in range(3):
    total = 0
    for m in range(5):
        total += marks [s][m]
    print("total for student",s,"is",total)

Notes:

  • Since you are trying to calculate the sum of a list you could use sum method

Upvotes: 2

Related Questions