'How do you find the sum of specific items in a 2d array with a foreach loop?

I have this list: my_list = [('a',1), ('b',2), ('c',3)]

How can i write a foreach loop to find the sum of 1+2+3?



Solution 1:[1]

Simplest approach:

list = [('a',1), ('b',2), ('c',3)]

summ = 0 # variable to store sum
for i in list:
    summ = summ + i[1]

print(summ)

This returns 6

Solution 2:[2]

Short approach using a comprehension:

items = [('a', 1), ('b', 2), ('c', 3)]
print(sum(item[1] for item in items))

Please avoid naming your list list, it's the name of the list type in Python, so you're "hiding" the list type, which can cause strange bugs if you need the real list later.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sibtain Reza
Solution 2 Julien Palard