i have this list: list = [('a',1), ('b',2), ('c',3)]
how can i write a foreach loop to find the sum of 1 2 3?
CodePudding user response:
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
CodePudding user response:
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.