Sum the values of two lists in Python

avatar

Borislav Hadzhiev

Last updated: Jul 4, 2022

banner

Check out my new book

Sum the values of two lists in Python #

To sum the values of two lists:

  1. Use the zip function to get an iterable of tuples with the corresponding items.
  2. Use a list comprehension to iterate over the iterable.
  3. Pass each tuple to the sum() function to get the sum.
main.py
list_1 = [1, 2, 3] list_2 = [4, 5, 6] # 👇️ [(1, 4), (2, 5), (3, 6)] print(list(zip(list_1, list_2))) list_3 = [sum(tup) for tup in zip(list_1, list_2)] print(list_3) # 👉️ [5, 7, 9]

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

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

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

The first tuple in the list consists of the elements in each list with an index of 0, the second tuple consists of the elements in each list that have an index of 1, and so on.

We used a list comprehension to iterate over the zip object.

main.py
list_1 = [1, 2, 3] list_2 = [4, 5, 6] list_3 = [sum(tup) for tup in zip(list_1, list_2)] print(list_3) # 👉️ [5, 7, 9]
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 also use this approach to sum the values of more than two lists.

main.py
list_1 = [1, 2, 3] list_2 = [4, 5, 6] list_3 = [7, 8, 9] list_4 = [sum(tup) for tup in zip(list_1, list_2, list_3)] print(list_4) # 👉️ [12, 15, 18]

Alternatively, you can use the map() function.

To sum the values of two lists:

  1. Call the map() function with the operator.add() method and the lists.
  2. Use the list() class to convert the map object to a list.
main.py
from operator import add list_1 = [1, 2, 3] list_2 = [4, 5, 6] list_3 = list(map(add, list_1, list_2)) print(list_3) # 👉️ [5, 7, 9]

Make sure to import the add() method from the operator module.

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

The operator.add method is the same as a + b.

You can imagine that map calls the add method with each item of the two iterables (e.g. items at index 0, then 1, etc).

The map function returns a map object, so we had to use the list() class to convert the result to a list.

Use the search field on my Home Page to filter through my more than 3,000 articles.