Klodiano
Klodiano

Reputation: 179

Python - Unsupported Operand type(s) for +: 'int' and 'list'

I'm attempting to find the average of a list within a list. My code :

Scores=[['James','Q',3,4,1,5],['Kat','L',3,4,1,2],['Maddy','G',3,5,6,4],['John','K',3,7,6,8],['Filip','NJ',3,8,9,9]]
size=len(Scores[3:5])
total=sum(Scores[3:5])
meanAverage=total/size
print(meanAverage)

The error I get is:

    total=sum(Scores[3:5])
TypeError: unsupported operand type(s) for +: 'int' and 'list'

Upvotes: 1

Views: 9367

Answers (2)

Kasravnd
Kasravnd

Reputation: 107287

You need to loop over your list, and attempt to apply the sum function on the last 4 items of sub-lists:

>>> [sum(i[3:5])/4 for i in Scores]
[1.25, 1.25, 2.75, 3.25, 4.25]

But note that if you want to get the number you need [2:6] slicing :

>>> [(i[2:6]) for i in Scores]
[[3, 4, 1, 5], [3, 4, 1, 2], [3, 5, 6, 4], [3, 7, 6, 8], [3, 8, 9, 9]]
>>> [sum(i[2:6])/4 for i in Scores]
[3.25, 2.5, 4.5, 6.0, 7.25]

Upvotes: 3

Jon Kiparsky
Jon Kiparsky

Reputation: 7743

scores[3:5] is looking up a slice from a list of lists. You want something like scores[0][3:5].

Upvotes: 1

Related Questions