As I've become more familiar with the NumPy and general scientific array processing ecosystem, it's become clearer to me that iteration is usually outright wrong due to how slow it is in comparison, and writing to use a vectorized operation is best whenever possible. Though the style is not as obvious/Pythonic at first, I've (anecdotally) gained ridiculous speedups with vectorized operations; more than 1000x in a case of swapping out a form like some row iteration .apply(lambda)

@MSeifert's answer much better provides this and will be significantly more performant on a dataset of any real size

More general Answer by @cs95 covering and comparing alternatives to iteration in Pandas


Original Answer

You can iterate through the values in your array with numpy.ndenumerate to get the indices of the values in your array.

Using the documentation above:

A = np.array([[1,2,3],[4,5,6],[7,8,9]])
for index, values in np.ndenumerate(A):
    print(index, values)  # operate here
Answer from ti7 on Stack Overflow
🌐
Medium
medium.com › @whyamit404 › understanding-numpy-enumerate-99426c85f779
Understanding numpy.enumerate. If you think you need to spend $2,000… | by whyamit404 | Medium
February 26, 2025 - Q2: Can I modify array elements while using enumerate()? Absolutely! In fact, this is one of the reasons enumerate() is so handy—you get the index, which allows you to modify elements directly. Here’s a quick example where we double all the even numbers in an array:
🌐
W3Schools
w3schools.com › python › numpy › numpy_array_iterating.asp
NumPy Array Iterating
import numpy as np arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) for x in np.nditer(arr[:, ::2]): print(x) Try it Yourself » · Enumeration means mentioning sequence number of somethings one by one.
Discussions

Iterate over numpy with index (numpy equivalent of python enumerate) - Stack Overflow
As your description of the problem ... for your example? So far sounds like you want a list/array of all pairs of indexes. ... Thanks for the suggested clarification! Let me know if it's still not clear. ... A list/array is fine but even more simply I just need to retrieve the two index values within each iteration as I will feed these into another formula immediately after retrieving them. ... As I've become more familiar with the NumPy and general ... More on stackoverflow.com
🌐 stackoverflow.com
Python enumerate through 2D array in numpy - Stack Overflow
I want a function that behaves like enumerate, but on numpy arrays. >>> list(enumerate("hello")) [(0, "h"), (1, "e"), (2, "l"), (3, "l"), (4, "o")] >>> for x, y, element in enum... More on stackoverflow.com
🌐 stackoverflow.com
python - How to iterate 1d NumPy array with index and value - Stack Overflow
For python dict, I could use iteritems() to loop through key and value at the same time. But I cannot find such functionality for NumPy array. I have to manually track idx like this: idx = 0 for j in theta: some_function(idx,j,theta) idx += 1 ... You can use enumerate for this.. More on stackoverflow.com
🌐 stackoverflow.com
python - How to iterate 1d NumPy array with index and value - Stack Overflow
For python dict, I could use iteritems() to loop through key and value at the same time. But I cannot find such functionality for NumPy array. I have to manually track idx like this: Copyidx = 0 for j in theta: some_function(idx,j,theta) idx += 1 ... You can use enumerate for this.. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Mimo
mimo.org › glossary › python › enumerate-function
Python enumerate(): Loop with an Index and start=
import numpy as np array = np.array([10, 20, 30, 40]) for i, value in enumerate(array): print(f"Index {i}: {value}") # Outputs: # Index 0: 10 # Index 1: 20 # Index 2: 30 # Index 3: 40
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.ndenumerate.html
numpy.ndenumerate — NumPy v2.5 Manual
January 31, 2021 - >>> import numpy as np >>> a = np.array([[1, 2], [3, 4]]) >>> for index, x in np.ndenumerate(a): ...
🌐
Scaler
scaler.com › home › topics › what is the equivalent of enum in numpy?
What is the equivalent of an enum in NumPy? | Scaler Topics
May 4, 2023 - Iterating over an array arr1 using index and item as iterables in for loop with np.ndenumerate, we get pairs of elements and their indices as output. Here we can see there are two values in the index, one for a row and the second one for a column element 1 is at the 0th row and 0th column, element 3 is at the 0th row and 1st column, and so on. ... In the above code example, a 1-D array arr is created using the np.arange function and then transformed into 3-D using the np.reshape function.
Top answer
1 of 3
19

As I've become more familiar with the NumPy and general scientific array processing ecosystem, it's become clearer to me that iteration is usually outright wrong due to how slow it is in comparison, and writing to use a vectorized operation is best whenever possible. Though the style is not as obvious/Pythonic at first, I've (anecdotally) gained ridiculous speedups with vectorized operations; more than 1000x in a case of swapping out a form like some row iteration .apply(lambda)

@MSeifert's answer much better provides this and will be significantly more performant on a dataset of any real size

More general Answer by @cs95 covering and comparing alternatives to iteration in Pandas


Original Answer

You can iterate through the values in your array with numpy.ndenumerate to get the indices of the values in your array.

Using the documentation above:

A = np.array([[1,2,3],[4,5,6],[7,8,9]])
for index, values in np.ndenumerate(A):
    print(index, values)  # operate here
2 of 3
8

You can do it using np.ndenumerate but generally you don't need to iterate over an array.

You can simply create a meshgrid (or open grid) to get all indices at once and you can then process them (vectorized) much faster.

For example

>>> x, y = np.mgrid[slice(A.shape[0]), slice(A.shape[1])]
>>> x
array([[0, 0, 0],
       [1, 1, 1],
       [2, 2, 2]])
>>> y
array([[0, 1, 2],
       [0, 1, 2],
       [0, 1, 2]])

and these can be processed like any other array. So if your function that needs the indices can be vectorized you shouldn't do the manual loop!

For example to calculate the lattice distance for each point to a point say (2, 3):

>>> abs(x - 2) + abs(y - 3)
array([[5, 4, 3],
       [4, 3, 2],
       [3, 2, 1]])

For distances an ogrid would be faster. Just replace np.mgrid with np.ogrid:

>>> x, y = np.ogrid[slice(A.shape[0]), slice(A.shape[1])]
>>> np.hypot(x - 2, y - 3)  # cartesian distance this time! :-)
array([[ 3.60555128,  2.82842712,  2.23606798],
       [ 3.16227766,  2.23606798,  1.41421356],
       [ 3.        ,  2.        ,  1.        ]])
Find elsewhere
🌐
NumPy
numpy.org › doc › 2.2 › reference › generated › numpy.ndenumerate.html
numpy.ndenumerate — NumPy v2.2 Manual
>>> import numpy as np >>> a = np.array([[1, 2], [3, 4]]) >>> for index, x in np.ndenumerate(a): ...
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.ndenumerate.html
numpy.ndenumerate — NumPy v2.6.dev0 Manual
>>> import numpy as np >>> a = np.array([[1, 2], [3, 4]]) >>> for index, x in np.ndenumerate(a): ...
🌐
Digital Blackboard
digitalblackboard.io › python › numpyarrays › array-iteration
NumPy Array Iteration - Digital Blackboard
July 19, 2022 - 1for j in arr2: # for each row 2 for i in j: # for each element of the row 3 print(i) ... To return the indices and values at the same time, we can invoke the numpy.ndenumerate() function once again.
🌐
Analytics Vidhya
analyticsvidhya.com › home › iteration in python – enumerate(), item(), np.nditer(), iterrows()
Iteration in Python | enumerate(), item(), np.nditer(), iterrows()
October 22, 2024 - Using a for loop to iterate over a list only gives us access to every list element in each run, one after the other. If one also wants to access the index information, so where the list element we are iterating over is located, we can use enumerate(). As an example, have a look at how the for loop was converted by creating an areas list: Python Code:
🌐
GeeksforGeeks
geeksforgeeks.org › python › numpy-iterating-over-array
Numpy - Iterating Over Arrays - GeeksforGeeks
July 23, 2025 - import numpy as np arr = np.array([[1, 2], [3, 4]]) for element in np.nditer(arr, order='F'): print(element) ... For multidimensional arrays, we can use enumerate to access both the index and value during iteration.
Top answer
1 of 2
66

There are a few alternatives. The below assumes you are iterating over a 1d NumPy array.

Iterate with range

for j in range(theta.shape[0]):  # or range(len(theta))
   some_function(j, theta[j], theta)

Note this is the only of the 3 solutions which will work with numba. This is noteworthy since iterating over a NumPy array explicitly is usually only efficient when combined with numba or another means of pre-compilation.

Iterate with enumerate

for idx, j in enumerate(theta):
   some_function(idx, j, theta)

The most efficient of the 3 solutions for 1d arrays. See benchmarking below.

Iterate with np.ndenumerate

for idx, j in np.ndenumerate(theta):
   some_function(idx[0], j, theta)

Notice the additional indexing step in idx[0]. This is necessary since the index (like shape) of a 1d NumPy array is given as a singleton tuple. For a 1d array, np.ndenumerate is inefficient; its benefits only show for multi-dimensional arrays.

Performance benchmarking

# Python 3.7, NumPy 1.14.3

np.random.seed(0)

arr = np.random.random(10**6)

def enumerater(arr):
    for index, value in enumerate(arr):
        index, value
        pass

def ranger(arr):
    for index in range(len(arr)):
        index, arr[index]
        pass

def ndenumerater(arr):
    for index, value in np.ndenumerate(arr):
        index[0], value
        pass

%timeit enumerater(arr)    # 131 ms
%timeit ranger(arr)        # 171 ms
%timeit ndenumerater(arr)  # 579 ms
2 of 2
11

You can use numpy.ndenumerate for example

import numpy as np
test_array = np.arange(2, 3, 0.1)
for index, value in np.ndenumerate(test_array):
    print(index[0], value)

For more information refer to https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndenumerate.html

🌐
Python Like You Mean It
pythonlikeyoumeanit.com › Module3_IntroducingNumpy › ArrayTraversal.html
Iterating Over Arrays & Array-Traversal Order — Python Like You Mean It
NumPy provides valuable tools for iterating over any array, such that each element can be visited in the array, regardless of the array’s shape. For example, recall that Python’s built-in enumerate function permits us to produce each item in an iterable, along with its index of iteration:
🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.ndenumerate.html
numpy.ndenumerate — NumPy v2.1 Manual
>>> import numpy as np >>> a = np.array([[1, 2], [3, 4]]) >>> for index, x in np.ndenumerate(a): ...