Sum list of lists in Python

avatar

Borislav Hadzhiev

Last updated: Jul 4, 2022

banner

Check out my new book

Sum list of lists in Python #

To sum a list of lists:

  1. Use the zip function to get an iterator of tuples with the corresponding items.
  2. Use a list comprehension to iterate over the iterable.
  3. On each iteration, pass the tuple to the sum() function.
main.py
list_of_lists = [[1, 2], [3, 4], [5, 6]] # 👇️ [(1, 3, 5), (2, 4, 6)] print(list(zip(*list_of_lists))) result = [sum(l) for l in zip(*list_of_lists)] print(result) # 👉️ [9, 12]

The zip function iterates over several iterables in parallel and produces tuples with an item from each iterable.

main.py
list_of_lists = [[1, 2], [3, 4], [5, 6]] # 👇️ [(1, 3, 5), (2, 4, 6)] print(list(zip(*list_of_lists)))

We used the * iterable unpacking operator to unpack the nested lists in the call to the zip() function.

main.py
list_of_lists = [[1, 2], [3, 4], [5, 6]] # 👇️ [1, 2] [3, 4] [5, 6] print(*list_of_lists)

The * iterable unpacking operator enables us to unpack an iterable in function calls, in comprehensions and in generator expressions.

You can imagine that the zip() function iterates over the nested lists, taking 1 item from each.

main.py
list_of_lists = [[1, 2], [3, 4], [5, 6]] # 👇️ [(1, 3, 5), (2, 4, 6)] print(list(zip(*list_of_lists)))
The first tuple in the list consists of the elements in each nested list that have an index of 0, and the second tuple consists of the elements in each nested list that have an index of 1.

The last step is to use a list comprehension to iterate over the zip object and sum each tuple.

main.py
list_of_lists = [[1, 2], [3, 4], [5, 6]] result = [sum(l) for l in zip(*list_of_lists)] print(result) # 👉️ [9, 12]
List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

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

On each iteration, we pass the current tuple to the sum() function and get the total.

You can use this approach with a list that stores nested lists of arbitrary length.

main.py
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # 👇️ [(1, 4, 7), (2, 5, 8), (3, 6, 9)] print(list(zip(*list_of_lists))) result = [sum(l) for l in zip(*list_of_lists)] print(result) # 👉️ [12, 15, 18]
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.