Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 583
Ben Avatar asked Mar 12 '09 10:03

Ben


People also ask

How do you sum values in tuples list in Python?

How to find a sum of a tuple in Python. To find a sum of the tuple in Python, use the sum() method. Define a tuple with number values and pass the tuple as a parameter to the sum() function; in return, you will get the sum of tuple items.

How do you get a list of the first element of a list of tuples?

How to get the first element of each tuple in a list in Python? Use a for-loop to iterate through a list of tuples. Within the for-loop, use the indexing tuple[0] to access the first element of each tuple, and append it.

How do you add tuple values together?

Concatenating and Multiplying TuplesConcatenation is done with the + operator, and multiplication is done with the * operator. Because the + operator can concatenate, it can be used to combine tuples to form a new tuple, though it cannot modify an existing tuple. The * operator can be used to multiply tuples.

How do you sum two tuples in Python?

When it is required to add the tuples, the 'amp' and lambda functions can be used. The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.


1 Answers

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.

like image 139
David Z Avatar answered Oct 09 '22 06:10

David Z