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
Answer from jpp on Stack Overflow
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ stable โ€บ reference โ€บ arrays.nditer.html
Iterating over arrays โ€” NumPy v2.5 Manual
During iteration, you may want to use the index of the current element in a computation. For example, you may want to visit the elements of an array in memory order, but use a C-order, Fortran-order, or multidimensional index to look up values in a different array.
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

Discussions

python - Iterating over a numpy array - Stack Overflow
I am in python 2.7 and am using your solution with the itertools; i read in the comments that using itertools will be faster. however, (maybe cause I am in 2.7) i also had to unpack map in the for loop. for x, y in itertools.product(*map(xrange, array.shape)): ... There's a page in the NumPy Reference called "Iterating Over ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to Iterating NumPy Array?
Iterating over a NumPy array means accessing its elements (one by one, or by row/column) using loops or built-in functions. More on mindstick.com
๐ŸŒ mindstick.com
0
November 12, 2025
Iterating through a numpy array
A quick note to start: In numpy, the row index comes before the column index, so, for example, a 3x2 array would have the form [[1,2],[3,4],[5,6]]. In any case, for an nx2 array called arr you can iterate through the pairs (rows) as you would through elements of a regular sequence: for n in arr: n # is your pair For a 2xn array, you can use for i in xrange(arr.shape[1]): arr[:, i] # is your pair but there are a number of ways to do this second form. Here 's a stackoverflow entry that treats this question in more detail. Worth mentioning: In general, if you can avoid iterating over a numpy array, you should. The iteration sacrifices some of the performance improvements over regular python given by the C-implemented numpy arrays. Numpy (and scipy) have a large selection of functions that allow you to avoid iteration (especially by leveraging the axis keyword to perform some computation over a specific axis) -- so search through the docs a bit before committing to this route. (an example of what I mean: to obtain the mean value of each of your tuples, use np.mean(arr, axis=1) in the nx2 case or axis=0 in the 2xn case to get an n-lengthed sequence of the mean of each pair; there are many functions like this) More on reddit.com
๐ŸŒ r/learnpython
7
2
November 14, 2014
Why iterate over an array using the index?
You do it if there is something in your loop that will use an index rather than the elements of the array. For instance, sometimes you want to sample something from another array that is not your loop array A cleaner way to do it is by using enumerate function for i, item in enumerate(array): The index gets assigned to i and whatever element of the array gets assigned to item. This may also be a bad habit from Matlab, people that come from Matlab are more used to looping over indexes. More on reddit.com
๐ŸŒ r/learnpython
57
46
April 22, 2023
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.        ]])
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.1 โ€บ reference โ€บ arrays.nditer.html
Iterating over arrays โ€” NumPy v2.1 Manual
During iteration, you may want to use the index of the current element in a computation. For example, you may want to visit the elements of an array in memory order, but use a C-order, Fortran-order, or multidimensional index to look up values in a different array.
๐ŸŒ
NumPy
numpy.org โ€บ devdocs โ€บ reference โ€บ arrays.nditer.html
Iterating over arrays โ€” NumPy v2.6.dev0 Manual
During iteration, you may want to use the index of the current element in a computation. For example, you may want to visit the elements of an array in memory order, but use a C-order, Fortran-order, or multidimensional index to look up values in a different array.
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.2 โ€บ reference โ€บ arrays.nditer.html
Iterating over arrays โ€” NumPy v2.2 Manual
During iteration, you may want to use the index of the current element in a computation. For example, you may want to visit the elements of an array in memory order, but use a C-order, Fortran-order, or multidimensional index to look up values in a different array.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ numpy โ€บ numpy_iterating_over_array.htm
NumPy - Iterating Over Array
In NumPy, arrays are indexed starting from 0 for each dimension. Iterating with indices involves using nested loops to traverse through each dimension of the array and access elements using their specific indices.
Find elsewhere
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ numpy โ€บ numpy_array_iterating.asp
NumPy Array Iterating
Iterating means going through elements one by one. As we deal with multi-dimensional arrays in numpy, we can do this using basic for loop of python.
๐ŸŒ
Hyperskill
hyperskill.org โ€บ university โ€บ numpy โ€บ numpy-array-iterating
NumPy Array Iterating
September 4, 2024 - To iterate over NumPy arrays without using the nditer object, you can use other built-in functions. The most straightforward way is to use the ndenumerate function, which returns an iterator yielding index and value pairs of the array.
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.3 โ€บ reference โ€บ arrays.nditer.html
Iterating over arrays โ€” NumPy v2.3 Manual
During iteration, you may want to use the index of the current element in a computation. For example, you may want to visit the elements of an array in memory order, but use a C-order, Fortran-order, or multidimensional index to look up values in a different array.
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.4 โ€บ reference โ€บ arrays.nditer.html
Iterating over arrays โ€” NumPy v2.4 Manual
During iteration, you may want to use the index of the current element in a computation. For example, you may want to visit the elements of an array in memory order, but use a C-order, Fortran-order, or multidimensional index to look up values in a different array.
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ how to iterate over a numpy array
How to Iterate over a NumPy Array - Be on the Right Side of Change
August 16, 2022 - The output is sent to the terminal. Then idx displays a Tuple containing the index value of the array and then the value of x for each iteration. This method uses a for loop and range()) to iterate through a 3D NumPy array.
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ numpy โ€บ numpy iterating over array
NumPy Iterating Over Array - Scaler Topics - Scaler Topics
September 9, 2022 - The array representation with its ... in the ... For iterating over an array in Python using a single iteration, nditer functions with loops like the for loop and while loop can access an element....
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.0 โ€บ reference โ€บ arrays.nditer.html
Iterating over arrays โ€” NumPy v2.0 Manual
During iteration, you may want to use the index of the current element in a computation. For example, you may want to visit the elements of an array in memory order, but use a C-order, Fortran-order, or multidimensional index to look up values in a different array.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ numpy-iterating-over-array
Numpy - Iterating Over Arrays - GeeksforGeeks
July 23, 2025 - For multidimensional arrays, we can use enumerate to access both the index and value during iteration. ... import numpy as np # Create a 2D array arr = np.array([[10, 20], [30, 40]]) # Enumerate through rows for idx, row in enumerate(arr): ...
๐ŸŒ
MindStick
mindstick.com โ€บ interview โ€บ 34411 โ€บ how-to-iterating-numpy-array
How to Iterating NumPy Array? โ€“ MindStick
November 12, 2025 - import numpy as np arr = np.array([1, 2, 3, 4, 5]) for x in arr: print(x) ... You can convert elements while iterating, e.g. from int to float: for x in np.nditer(arr, flags=['buffered'], op_dtypes=['float']): print(x) ... arr = np.array([[1, ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ iterating through a numpy array
r/learnpython on Reddit: Iterating through a numpy array
November 14, 2014 -

I know this is a dumb question, but I've scoured Google for the documentation, Stack Overflow, etc. but I can't figure out how to do this. I'm really used to C so I might be approaching this wrong.

Basically, I have a multidimensional array; specifically, it's n x 2. Another way of looking at it is that it's an array of tuples.

So suppose there are the points (1, 9), (2, 8), and (3, 7).

Now, my assumption is that [[1, 2, 3], [9, 8, 7]] is an nx2 array, and that [[1,9], [2, 8], [3, 7]] is a 2xn array, correct?

So my question is, in each case (given an nx2 and a 2xn array), how would I iterate through each ordered pair?

๐ŸŒ
Kaggle
kaggle.com โ€บ general โ€บ 521858
Numpy Arrays Iterating | Kaggle
The ndenumerate() function allows us to iterate through a NumPy array while also keeping track of the index of each element. This is useful for cases where We need both the index and the value.
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ 5 best ways to loop through numpy arrays in python
5 Best Ways to Loop Through NumPy Arrays in Python - Be on the Right Side of Change
February 20, 2024 - The numpy.nditer() function provides an efficient way to iterate over array elements. By using this iterator object, we can achieve better performance than a vanilla for-loop, which is especially noticeable with multi-dimensional arrays.