Sum two arrays python

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,

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,

Frequently Asked:

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)

We added both the lists element wise.

Читайте также:  Java option heap size

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)

We added both the lists element wise.

Summary

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

Share your love

Leave a Comment Cancel Reply

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

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

How to Sum Elements of Two Lists in Python: Comprehensions and More

How to Sum Elements of Two Lists in Python Featured Image

Welcome back to another edition of the How to Python series. This time I want to sum elements of two lists in Python. I got the inspiration for this topic while trying to do just this at work the other day. In short, one of the best ways to sum elements of two lists in Python is to use a list comprehension in conjunction with the addition operator. For example, we could perform an element-wise sum of two lists as follows: `[x + y for x, y in zip(list_a, list_b)]`python. But, as always, we’ll take a look at other options.

Table of Contents

Video Summary

Opens in a new tab.

Are there any better ways to get this working?

A Little Recap

ethernet_devices = [1, [7], [2], [8374163], [84302738]] usb_devices = [1, [7], [1], [2314567], [0]] # The long way all_devices = [ ethernet_devices[0] + usb_devices[0], ethernet_devices[1] + usb_devices[1], ethernet_devices[2] + usb_devices[2], ethernet_devices[3] + usb_devices[3], ethernet_devices[4] + usb_devices[4] ] # Some comprehension magic all_devices = [x + y for x, y in zip(ethernet_devices, usb_devices)] # Let's use maps import operator all_devices = list(map(operator.add, ethernet_devices, usb_devices)) # We can't forget our favorite computation library import numpy as np all_devices = np.add(ethernet_devices, usb_devices)

Opens in a new tab.

As we can see, there are a lot of ways to run an element-wise sum of two lists. Take your pick. As always, thanks for stopping by! If you liked this article, I have a massive list of code snippets just like this for your perusal. If you’re interested in learning more about Python, consider subscribing to The Renegade Coder—or at least hop on our mailing list, so you’ll never miss another article. Tune in next time to learn how to check if a file exists in Python. While you’re here, you might be interested in some these other Python articles:

  • How to Automate Your GitHub Wiki
  • How I Automated My Grading Responsibilities
  • Reverse a String in Python

Once again, thanks for stopping by. I appreciate it!

How to Python (42 Articles)—Series Navigation

The How to Python tutorial series strays from the usual in-depth coding articles by exploring byte-sized problems in Python. In this series, students will dive into unique topics such as How to Invert a Dictionary, How to Sum Elements of Two Lists, and How to Check if a File Exists.

Each problem is explored from the naive approach to the ideal solution. Occasionally, there’ll be some just-for-fun solutions too. At the end of every article, you’ll find a recap full of code snippets for your own use. Don’t be afraid to take what you need!

Opens in a new tab.

If you’re not sure where to start, I recommend checking out our list of Python Code Snippets for Everyday Problems. In addition, you can find some of the snippets in a Jupyter notebook format on GitHub,

If you have a problem of your own, feel free to ask. Someone else probably has the same problem. Enjoy How to Python!

Источник

Numpy – Elementwise sum of two arrays

In this tutorial, we will look at how to get a numpy array resulting from the elementwise sum of two numpy arrays of the same dimensions.

Add two numpy arrays

Elementwise sum of a 2d numpy array

You can use the numpy np.add() function to get the elementwise sum of two numpy arrays. The + operator can also be used as a shorthand for applying np.add() on numpy arrays. The following is the syntax:

📚 Discover Online Data Science Courses & Programs (Enroll for Free)

Introductory ⭐

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

import numpy as np # x1 and x2 are numpy arrays of same dimensions # using np.add() x3 = np.add(x1, x2) # using + operator x3 = x1 + x2

It returns a numpy array resulting from the elementwise addition of each array value.

Let’s look at some examples of adding numpy arrays elementwise –

Add two 1d arrays elementwise

To elementwise add two 1d arrays, pass the two arrays as arguments to the np.add() function. Let’s show this with an example.

import numpy as np # create numpy arrays x1 and x2 x1 = np.array([1, 3, 0, 7]) x2 = np.array([2, 0, 1, 1]) # elementwise sum with np.add() x3 = np.add(x1, x2) # display the arrays print("x1:", x1) print("x2:", x2) print("x3:", x3)
x1: [1 3 0 7] x2: [2 0 1 1] x3: [3 3 1 8]

The array x3 is the result of the elementwise summation of values in the arrays x1 and x2.

Alternatively, you can also use the + operator to add numpy arrays elementwise.

# elementwise sum with + operator x3 = x1 + x2 # display the arrays print("x1:", x1) print("x2:", x2) print("x3:", x3)
x1: [1 3 0 7] x2: [2 0 1 1] x3: [3 3 1 8]

You can see that we get the same results as above with x3 as the array resulting from the elementwise sum of arrays x1 and x2.

Add two 2d arrays elementwise

The syntax for adding higher-dimensional arrays is also the same. Pass the two arrays to the np.add() function which then returns a numpy array resulting from elementwise addition of the values in the passed arrays.

# create 2d arrays x1 and x2 x1 = np.array([[1, 0, 1], [2, 1, 1], [3, 0, 3]]) x2 = np.array([[2, 2, 0], [1, 0, 1], [0, 1, 0]]) # elementwise sum with np.add() x3 = np.add(x1, x2) # display the arrays print("x1:\n", x1) print("x2:\n", x2) print("x3:\n", x3)
x1: [[1 0 1] [2 1 1] [3 0 3]] x2: [[2 2 0] [1 0 1] [0 1 0]] x3: [[3 2 1] [3 1 2] [3 1 3]]

Here, we add two 3×3 numpy arrays. The values in the array x3 are the result of the elementwise sum of values in the arrays x1 and x2.

Again, you can also use the + operator to perform the same operation.

# elementwise sum with + opeartor x3 = np.add(x1, x2) # display the arrays print("x1:\n", x1) print("x2:\n", x2) print("x3:\n", x3)
x1: [[1 0 1] [2 1 1] [3 0 3]] x2: [[2 2 0] [1 0 1] [0 1 0]] x3: [[3 2 1] [3 1 2] [3 1 3]]

Add more than two arrays elementwise

You can use the + operator to add (elementwise) more than two arrays as well. For example, let’s add three 1d arrays elementwise.

# create numpy arrays x1, x2, and x3 x1 = np.array([1, 3, 0, 7]) x2 = np.array([2, 0, 1, 1]) x3 = np.array([0, 1, 3, 1]) # elementwise sum with + x4 = x1+x2+x3 # display the arrays print("x1:", x1) print("x2:", x2) print("x3:", x3) print("x4:", x4)
x1: [1 3 0 7] x2: [2 0 1 1] x3: [0 1 3 1] x4: [3 4 4 9]

Here, the array x4 is the result of the elementwise sum of the arrays x1, x2, and x3.

What if the arrays have different dimensions?

# add two arrays with different dimensions x1 = np.array([1, 3, 0, 7]) x2 = np.array([2, 0, 1, 1, 1]) x3 = np.add(x1, x2)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) in 2 x1 = np.array([1, 3, 0, 7]) 3 x2 = np.array([2, 0, 1, 1, 1]) ----> 4 x3 = np.add(x1, x2) ValueError: operands could not be broadcast together with shapes (4,) (5,)

Trying to add two numpy arrays of different dimensions results in an error. This is because it doesn’t make sense to elementwise add two arrays that don’t have the same dimensions.

For more on the numpy np.add() function, refer to its documentation.

With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having numpy version 1.18.5

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

  • How to sort a Numpy Array?
  • Create Pandas DataFrame from a Numpy Array
  • Different ways to Create NumPy Arrays
  • Convert Numpy array to a List – With Examples
  • Append Values to a Numpy Array
  • Find Index of Element in Numpy Array
  • Read CSV file as NumPy Array
  • Filter a Numpy Array – With Examples
  • Python – Randomly select value from a list
  • Numpy – Sum of Values in Array
  • Numpy – Elementwise sum of two arrays
  • Numpy – Elementwise multiplication of two arrays
  • Using the numpy linspace() method
  • Using numpy vstack() to vertically stack arrays
  • Numpy logspace() – Usage and Examples
  • Using the numpy arange() method
  • Using numpy hstack() to horizontally stack arrays
  • Trim zeros from a numpy array in Python
  • Get unique values and counts in a numpy array
  • Horizontally split numpy array with hsplit()

Author

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts

Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.

Источник

Оцените статью