Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How would I perform an operation on each element in an array and add the new value to a new array in Python?

I have an array of ten random values generated using Numpy. I want to perform an operation on each element in the array by looping over all ten elements and then add the result of each to a new array. The first part of looping over the array but I am stuck on how to add the result to a new array.

So far I have tried something along the lines of:

import numpy as np

array = np.random.rand(10)

empty_array = np.zeros(10)

for elem in array:

    new_val = elem**2

where empty_array is an array of 10 elements set to zero, my logic being similar to initialising an empty list to add elements to when looping over another list or array. I am stuck on how to replace the corresponding elements of empty_array with the square of elements in ‘array’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any help on how to do this or a better way of doing this would be greatly appreciated!

>Solution :

You can append the new value like:

import numpy as np

array = np.random.rand(10)
new_array = []
for elem in array:
    new_array.append(elem ** 2)

Or using the list comprehension:

import numpy as np

array = np.random.rand(10)
new_array = [e**2 for e in array]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading