0

I am trying to iterate over the items of a numpy array using a for loop. Is there a way to keep track of the index of the current item of the iteration (other than initializing a counter before the loop and increment it inside the loop)?

myArray = [4 5 6 7]

for item in myArray:
    print(index of item)

What I would like to get is (keeping in mind that this is a numpy array, not a list)

0
1
2
3

2 Answers 2

1

you can iterate like this:

import numpy as np

a = np.array([6,5,7,0,1,3,4])

for index in range(a.shape[0]):  # use range with nparray.shape[0] to get the size
    print(index) # you can do a[index] to get the value

this outputs :

0
1
2
3
4
5
6
Sign up to request clarification or add additional context in comments.

1 Comment

Works well but not the right way of doing it since I am trying to access the items inside the loop as well; not just printing the index. But thanks for the answer!
0

The right way to do this is to use enumerate:

myArray = [4, 5, 6, 7]

for i,item in enumerate(myArray):
    print(i)

1 Comment

Great. This is exactly what I was looking for. I achieved this with a pandas dataframe using for index, row in df.iterrows(): and was looking to do the same thing for an array.

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.