Categories
Python Answers

How to do an element-wise addition of 2 lists with Python?

Spread the love

Sometimes, we want to do an element-wise addition of 2 lists with Python.

In this article, we’ll look at how to do an element-wise addition of 2 lists with Python.

How to do an element-wise addition of 2 lists with Python?

To do an element-wise addition of 2 lists with Python, we can use the operator.add method.

For instance, we write:

from operator import add

list1 = [1, 2, 3]
list2 = [4, 5, 6]
added = list(map(add, list1, list2))
print(added)

We call map with add and list1 and list2 to add the entries in list1 and list2 element-wise.

Then we call list to convert the returned iterable object back to a list.

Therefore, added is [5, 7, 9].

Conclusion

To do an element-wise addition of 2 lists with Python, we can use the operator.add method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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