user17344362
user17344362

Reputation:

How to print even index values of any array | NumPy |

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

Upvotes: 1

Views: 1525

Answers (2)

I'mahdi
I'mahdi

Reputation: 24069

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

Upvotes: 4

Jakub Szlaur
Jakub Szlaur

Reputation: 2132

  • 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 any range or length

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]

Upvotes: 2

Related Questions