Sum the second element of each tuple in a list in Python

avatar

Borislav Hadzhiev

Last updated: Jun 29, 2022

banner

Photo from Unsplash

Sum the second element of each tuple in a list in Python #

Use a generator expression to sum the second element of each tuple in a list, e.g. result = sum(tup[1] for tup in list_of_tuples). The sum() function gets passed a generator object with the second element of each tuple in the list and returns the total.

main.py
list_of_tuples = [(10, 20), (30, 40), (50, 60)] result = sum(tup[1] for tup in list_of_tuples) print(result) # 👉️ 120

The first step is to use a generator expression to iterate over the list of tuples.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we access the tuple element at index 1 (the second tuple item) and return the result.

The example passes a generator object that contains the numbers 20, 40, 60 to the sum() function, which then returns 120.

You can use this approach to sum the Nth element of each tuple in a list.

Here is an example that sums the first element of each tuple in a list.

main.py
list_of_tuples = [(10, 20), (30, 40), (50, 60)] result = sum(tup[0] for tup in list_of_tuples) print(result) # 👉️ 90
Python indexes are zero-based. The first item in a tuple (or any other iterable) has an index of 0, the second an index of 1, etc.

An alternative approach is to unpack the second item from each tuple in the generator expression.

main.py
list_of_tuples = [(10, 20), (30, 40), (50, 60)] result = sum(second for _, second in list_of_tuples) print(result) # 👉️ 120

We only assigned the second item in the tuples to a variable.

The first item is stored in an underscore because it's not needed.

We basically unpack the second item from the tuple of the current iteration and assign the value to a variable.

main.py
first, second = (10, 20) print(first) # 👉️ 10 print(second) # 👉️ 20

When using this approach, you have to make sure to declare exactly as many variables as you have items in the tuple.

Which approach you pick is a matter of personal preference. I'd use directly index access as if I find it easier to read and more explicit.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.