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

Time:04-07

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.

CodePudding user response:

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)

CodePudding user response:

Your code gets 3rd integer of each i-th sub-array separately and can't sum int to itself. Here is right way to do this:

arr = [[10, 12, 22], [18, 20, 38], [32, 35, 67], [57, 66, 123], [103, 121, 224]]
s = 0
for i in range(len(arr)):
    s  = arr[i][2]
print(f"The sum of every 3rd element within each sub array is {s}

CodePudding user response:

Yes, you make a stupid mistake ;-). This: sum(list[i][2]) means you are summing over the second element over the list[i] which is an int. And this is not iterable. Using a list comprehension this does the trick

print(f"The sum of every 3rd {sum([j[2] for j in list])}")
  • Related