I am a learner , bit stuck not getting how do i print the even indexed value of an array
My code :
import numpy as np
arr_1 = np.array([2,4,6,11])
arr_1 [ (arr_1[ i for i in range(arr_1.size) ] ) % 2 == 0 ]
Expected Output :
2,6
2 -> comes under index 0
6 -> comes under index 2
Both are even index
CodePudding user response:
IIUC, You can use [start:end:step]
from list
and get what you want like below:
>>> arr_1 = np.array([2,4,6,11])
>>> arr_1[::2]
array([2, 6])
>>> list(arr_1[::2])
[2, 6]
>>> print(*arr_1[::2], sep=',')
2,6
CodePudding user response:
May be this could work for you
Code :
import numpy as np
arr_1 = np.array([2,4,6,11])
a = [ arr_1[i] for i in range(arr_1.size) if ((i % 2) == 0) ]
print(a)
Code is run in google Colab
CodePudding user response:
- Your problem was that you were iterating through what
range()
function returned. - which obviously wasn't your original
arr_1
- in my code we just iterate through the
arr_1
without using anyrange
orlength
Code that will work:
import numpy as np
arr_1 = np.array([2,4,6,11])
arr_1 = [i for index, i in enumerate(arr_1) if ((index % 2) == 0)]
print(arr_1)
Output:
[2, 6]