Find sum of two lists in Python

In this article, we will discuss different ways to get the sum of two lists element wise and store that to a new list in Python.

Table Of Contents

Introduction

Suppose we have two lists,

firstList   = [21, 23, 13, 44, 11, 19]
secondList  = [49, 48, 47, 46, 45, 44]

Now we want to add these two lists element wise and store the result in an another list. Contents of this merged list will be,

[70, 71, 60, 90, 56, 63]

In the above example, nth item of first list should be added to the nth item of second list, and summed up values should be added to a new list. There are different ways to do this. Let’s discuss them one by one,

Find sum of two lists using zip() and List Comprehension

Pass both the lists to zip() function as arguments. It will return a zipped object, which yields tuples, containing an item from both the lists, until an any one list is exhaused. We can add the items in each of the returned tuple and store the result in a new list. In the end we will get a list containing the sum of two lists element wise. For example,

firstList   = [21, 23, 13, 44, 11, 19]
secondList  = [49, 48, 47, 46, 45, 44]

# get the sum of two lists element wise
mergedList = [sum(x) for x in zip(firstList, secondList)]

print(mergedList)

Output:

[70, 71, 60, 90, 56, 63]

We added both the lists element wise.

Find sum of two lists using for loop

Create a new empty list. Then, select the smallest list out of the two given lists. Get the size of that smallest list. Iterate from 0 till the size of smallest list. In each ith iteration of for loop, get the sum of values at ith index in both the list and store that at ith position in new list. For example,

firstList   = [21, 23, 13, 44, 11, 19]
secondList  = [49, 48, 47, 46, 45, 44]

size = min(len(firstList), len(secondList))

# get the sum of two lists element wise
mergedList = []
for i in range(size):
    value = firstList[i] + secondList[i]
    mergedList.append(value)

print(mergedList)

Output:

[70, 71, 60, 90, 56, 63]

We added both the lists element wise.

Summary

We learned how to get the sum of two lists in Python. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top