-2

Assuming I have this list of tuples: [('3', '20'), ('1', '50'), ('2', '50')], how would I go about summing up only the second element in each tuple? So in this example, the sum would be 120. Also, would I have to convert the numbers to integers beforehand for the sum() function to work?

Delgan
  • 18,571
  • 11
  • 90
  • 141
kraderic
  • 1
  • 2

2 Answers2

0

If l is you list then:

sum(int(x[1]) for x in l)

Instead of sum(...) you can also use sum((...)) or sum([...]). The former uses a generator expression, the latter creates a temporary list (list comprehension).

Markus
  • 3,155
  • 2
  • 23
  • 33
  • You do not have to enclose your generator expression into parenthesis neither brackets. `sum(int(x[1]) for x in l)` works just fine. – Delgan Apr 25 '16 at 20:04
  • @Delgan Already modified while you wrote your comment. :-) – Markus Apr 25 '16 at 20:06
-4

you could try something like,

tup = [('3', '20'), ('1', '50'), ('2', '50')]
s= 0
for i in tup: 
    s+= int(i[-1])
jkhadka
  • 2,443
  • 8
  • 34
  • 56
  • This worked like a charm, thank you. Sorry to bother with a following question, but could you clarify what the [-1] does? Thank you so much. – kraderic Apr 25 '16 at 20:04
  • @kraderic When you use a negative index in a list, it counts from the end instead of the beginning. So `i[-1]` is the last element of the list. – Barmar Apr 25 '16 at 20:09
  • @kraderic [-1] refers to the last one. In this case, it's the same as [1]. Look http://stackoverflow.com/questions/509211/explain-pythons-slice-notation here for explanation. – Amit Gold Apr 25 '16 at 20:09
  • 1
    However, the question specifically says "the second element", not "the last element". In the example given they're the same, but that's not necessarily the case in general. – Barmar Apr 25 '16 at 20:10
  • So "i" is referring to the individual pairs in the tuple, and then [-1] means it's only registering the last element in each pair? – kraderic Apr 25 '16 at 20:11
  • @kraderic yes, by doing `for i in tup`, `i` is picking up one by one element of `tup`, so in first round `i = ('3','20')` and second round `i = ('1','50')` and so on. and then by doing `i[-1]` you get the last element or you could do `i[1]` which gives second element. Python counts from `0` so `i[0]` is first element. – jkhadka Apr 25 '16 at 20:22