Search code snippets, questions, articles...

Create a List from sum of two Lists in Python

In this post, we are going to explain some methods and techniques that can be used to get the sum of two lists element wise in the final list.
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

Python List is a collection of iterable elements that can contain any type of item in it. 

Here, we are going to calculate the sum of two or multiple Lists elements index-wise and generate a new list from the sum. Suppose we have two lists that contain multiple numeric type items.

Create two Python Lists

# define two lists
list1 = [10, 9, 13, 19, 25, 81, 51]
list2 = [4, 10, 13, 21, 19, 5, 1]

Using the above two lists we want to generate the output list that will look like below.

[14, 19, 26, 40, 44, 86, 52]

Below are the methods that can be used to get the new list that will contain the sum of elements with their respective index.

Using zip() and List Comprehension to get the sum of two lists

This is a pythonic way to generate a new list that will contain the sum of items. We will be using the zip() function and List Comprehension for that.

Code Example

# define two lists
list1 = [10, 9, 13, 19, 25, 81, 51]
list2 = [4, 10, 13, 21, 19, 5, 1]

# use zip() function to calculate the sum of lists
result = [x + y for x, y in zip(list1, list2)]

# print the result
print(result)

Output

[14, 19, 26, 40, 44, 86, 52]

If you have a list of lists and want to get the list that will contain the total of the two lists then you can use the below code example.

my_list = [[10, 20, 30, 40, 10], [30, 10, 40, 20, 5]]

result_list = [sum(x) for x in zip(*my_list)]

print(result_list)

Output

[40, 30, 70, 60, 15]

Method 2: Using map() and lambda functions

We can also use map() and lambda functions to make a list that contains the sum of two lists. We have created two lists list1 and list2 here and created a new list result using map and lambda functions.

list(map(lambda a,b: a+b, list1, list2))

Full Code Example

# define two lists
list1 = [1, 2, 3, 4, 5, 6, 7]
list2 = [10, 20, 30, 40, 50, 60, 70]

# use map() and lambda function to get the sum
result = list(map(lambda a,b: a+b, list1, list2))

# print the result
print(result)

Output

[14, 19, 26, 40, 44, 86, 52]

Method 3: Using numpy add() function

If you are using numpty in your project then you can use its add() function to generate the sum of two lists. Below is the code example.

list(np.add(list1, list2))
import numpy as np

# define two lists
list1 = [10, 20, 30, 40, 10]
list2 = [30, 10, 40, 20, 5]

# use np.add() function
result = list(np.add(list1, list2))

# print the result
print(result)

Output

[40, 30, 70, 60, 15]
Was this helpful?
0 Comments