Ben Ben - 2 years ago 90
Python Question

How do I sum the first value in each tuple in a list of tuples in Python?

I have a list of tuples (always pairs) like this:

[(0, 1), (2, 3), (5, 7), (2, 1)]

I'd like to find the sum of the first items in each pair, i.e.:

0 + 2 + 5 + 2

How can I do this in Python? At the moment I'm iterating through the list:

sum = 0
for pair in list_of_pairs:
sum += pair[0]

I have a feeling there must be a more Pythonic way.

Answer Source

A version compatible with Python 2.3 is

sum([pair[0] for pair in list_of_pairs])

or in recent versions of Python, see this answer or this one.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download