Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to sum specific elements of a list with a "for i in range(len(list))" loop

list=[[10,12,22],[18,20,38],[32,35,67],[57,66,123],[103,121,224]] 

This is the list that I am looping through.

for i in range(len(list)):
    print(f"The sum of every 3rd element within each sub list is {sum(list[i][2])}

When I run this, the error message is:

TypeError: 'int' object is not iterable

Is this simply not possible to do or am I making a stupid mistake?
I am quite new to coding so apologies for what may seem like a very stupid question to some.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I’ll help you out. First don’t use python keywords as a variable name – so list is not good. Secondly I see so many people iterating over the range of the list and then referencing by index. This isn’t necessary.

l =[[10,12,22],[18,20,38],[32,35,67],[57,66,123],[103,121,224]]

How I often see it done

for i in range(len(l)):
    print(l[i][2])

How it probably should be done

for x in l:
    print(x[2])

And the answer you are looking for:

sum(x[2] for x in l)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading