0

I want to square even index values in numpy array and assign same in that array. I followed 2 approaches.

1 -

for i in range(len(arr)):
        if i %2 == 0:
            arr[i] = arr[i]**2

That is working.

2 -

arr[i] = arr[i]**2 for i in range(len(arr)) if i % 2 == 0

 File "<ipython-input-149-30fc7ed25f1f>", line 1
    arr[i] = arr[i]**2 for i in range(len(arr)) if i % 2 == 0
                     ^
SyntaxError: invalid syntax

not working.

Is some syntax error?

1
  • 1
    Don't loop over a numpy array, you lose the power of the optimized code. Rather use np.where - see my answer below. Commented Apr 26, 2019 at 7:02

3 Answers 3

2

This works with list compreension:

arr = [arr[i]**2 if i % 2 == 0 else arr[i] for i in range(len(arr))]

But you could also use the shorter:

arr[::2] = arr[::2]**2
Sign up to request clarification or add additional context in comments.

1 Comment

arr[::2] = arr[::2]**2 is by far the best and mosty numpy-style solution of all solutions!
0

I assume you are trying to do list comprehension, for which your syntax is slightly off, read up on the syntax of list comprehension.
It's syntax is similar to [exp1(item) if condition1 else exp2(item) for item in arr] .
The correct way to do it is as follows.

arr = [1,2,3,4,5,6]
arr = [arr[i]**2 if i % 2 == 0 else arr[i] for i in range(len(arr))]
print(arr)
#[1, 2, 9, 4, 25, 6]

What this is doing is running the for loop, checking the condition, and then picking either arr[i] or arr[i]**2, and then assigning the result to the list

3 Comments

This is not a numpy solution?
Nowhere has the OP use numpy in his code! So I provided a generic solution
True, but he specifically mentions just before the code that he is using a numpy array...
0

Dont loop over numpy arrays you lose all the power of numpy.

Use these numpy functions to achieve the required result instead:

import numpy as np
arr = np.random.randint(0,10, size=(10,))
print(arr)
ans = np.where(np.arange(10) % 2 == 0, arr, arr**2)
print(ans)

output:

[ 1 9   1  1  0 6   5  2  1 5 ]
[ 1 81  1  1  0 36  5  4  1 25]

np.where selects the elements where the condition is true. Then outputs either the original array or the squared array.

Docs for np.where.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.