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
Is there a better way to do this?
You can use
numpy.ndenumerate
for exampleFor more information refer to https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndenumerate.html
There are a few alternatives. The below assumes you are iterating over a 1d NumPy array.
Iterate with
range
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 withnumba
or another means of pre-compilation.Iterate with
enumerate
The most efficient of the 3 solutions for 1d arrays. See benchmarking below.
Iterate with
np.ndenumerate
Notice the additional indexing step in
idx[0]
. This is necessary since the index (likeshape
) 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