Lists and For Loops Assessment

Screen Link:
https://app.dataquest.io/m/2000312/lists-and-for-loops-assessment/3/question-3

My Code:

from csv import reader 

open_file = open('weightlifting.csv')
read_file = reader(open_file)
weightlifting_81kg = list(read_file)

header = weightlifting_81kg[0]
weightlifting_81kg = weightlifting_81kg[1:]

top_5 = weightlifting_81kg[:5]
top_5 = top_5[3]

average_snatch_top_5 = sum(top_5)/len(top_5)
print(average_snatch_top_5)

What I expected to happen:
I was hoping this would work

What actually happened:
I got this error message instead

Traceback (most recent call last):
  File "/tmp/e3b6eb9a00d6ded6fe346f2778ca172ac9a1beb9.py", line 86, in run_code_string
    exec(code, variables)
  File "<string>", line 13, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

I’m pretty sure im missing something basic and fundamental but not sure what it is. Could anyone help with this? Sorry if this is too simple

1 Like

Hi codingNotWorking

Welcome to the community!!

Here you are assigning the fourth element in the top_5 list to top_5.

I assume that you are trying to retrieve the snatch_kg values from top_5. By inspecting the header, you can see that
['name', 'country', 'snatch_kg', 'clean_jerk_kg', 'total']

So, snatch_kg is the 3rd column but in a List, the first index is 0. Hence, in order to fetch the snatch_kg values from top_5, we’ll have to write, top_5[0][2].

Here, top_5[0] will retrieve the first row in the list (top_5 is a list of lists):
['Lu Xiaojun', 'China', '171', '207', '378']

Again, top_5[0][2] will fetch us '171'. And, this value (‘171’) is a string here. So we have to convert it to int.

So to find the sum of snatch_kg in top_5, we’ll have to write

int(top_5[0][2]) + int(top_5[1][2]) + int(top_5[2][2]) + int(top_5[3][2]) + int(top_5[4][2])

Hope this helps.

2 Likes

Hi Dash,
Thank you so much for taking the time to write all that out!
I did think the solution was longer but I didn’t want to write “too much code” Sorry, hope to figure it out eventually!
Thank you
C