How do I sum the first value in each tuple in a list of tuples in Python?
sum(i for i, j in list_of_pairs)
will do too.
If you have a very large list or a generator that produces a large number of pairs you might want to use a generator based approach. For fun I use itemgetter()
and imap()
, too. A simple generator based approach might be enough, though.
import operator
import itertools
idx0 = operator.itemgetter(0)
list_of_pairs = [(0, 1), (2, 3), (5, 7), (2, 1)]
sum(itertools.imap(idx0, list_of_pairs))
Note that itertools.imap()
is available in Python >= 2.3. So you can use a generator based approach there, too.
In modern versions of Python I'd suggest what SilentGhost posted (repeating here for clarity):
sum(i for i, j in list_of_pairs)
In an earlier version of this answer I had suggested this, which was necessary because SilentGhost's version didn't work in the version of Python (2.3) that was current at the time:
sum([pair[0] for pair in list_of_pairs])
Now that version of Python is beyond obsolete, and SilentGhost's code works in all currently-maintained versions of Python, so there's no longer any reason to recommend the version I had originally posted.
I recommend:
sum(i for i, _ in list_of_pairs)
Note:
Using the variable _
(or __
to avoid confliction with the alias of gettext
) instead of j
has at least two benefits:
_
(which stands for placeholder) has better readabilitypylint
won't complain: "Unused variable 'j'"