Sum the elements of a tuple in Python

Borislav Hadzhiev

Last updated: Jun 29, 2022

Photo from Unsplash

**Use the sum() function to sum the elements of a tuple, e.g.
result = sum(my_tuple). The sum function takes an iterable (such as a tuple)
as an argument, sums its items from left to right and returns the total.**

main.py

`my_tuple = (10, 20, 30) # ✅ sum the elements of a tuple result = sum(my_tuple) print(result) # 👉️ 60 # -------------------------------- # ✅ sum the elements of each tuple in a list of tuples list_of_tuples = [(10, 20), (30, 40), (50, 60)] result_2 = [sum(t) for t in list_of_tuples] print(result_2) # 👉️ [30, 70, 110] # ---------------------------------- # ✅ sum the elements at index `0` of each tuple in a list result_3 = sum(tup[0] for tup in list_of_tuples) print(result_3) # 👉️ 90`

We used the `sum()`

function to sum the elements of a tuple.

main.py

`my_tuple = (10, 20, 30) result = sum(my_tuple) print(result) # 👉️ 60`

The sum function takes an iterable, sums its items from left to right and returns the total.

The function takes the following 2 arguments:

Name | Description |
---|---|

iterable | the iterable whose items to sum |

start | sums the `start` value and the items of the iterable. `sum` defaults to `0` (optional) |

If you need to sum the elements of each tuple in a list, use a list comprehension.

main.py

`# ✅ sum the elements of each tuple in a list of tuples list_of_tuples = [(10, 20), (30, 40), (50, 60)] result_2 = [sum(t) for t in list_of_tuples] print(result_2) # 👉️ [30, 70, 110]`

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

In the example, we iterate over the list and pass each tuple to the `sum()`

function to sum its elements.

The first tuple has a sum of `30`

, the second a sum of `70`

, and the third a sum
of `110`

.

If you need to sum the elements at index N of each tuple in a list, use a generator expression.

main.py

`# ✅ sum the elements at index `0` of each tuple in a list list_of_tuples = [(10, 20), (30, 40), (50, 60)] result_3 = sum(tup[0] for tup in list_of_tuples) print(result_3) # 👉️ 90`

Generator expressions are also 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 `0`

(the first tuple
item) and return the result.

The example passes a generator object that contains the numbers `10`

, `30`

, `50`

to the `sum()`

function which then returns `90`

.