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.
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 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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With