Skip to content
Advertisement

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’.

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

Advertisement

Answer

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]
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement