NumPy: Enumerated Iteration Using ndenumerate()

Profile picture for user devanshi.srivastava
Submitted by devanshi.srivastava on

Enumerated Iteration is used to mention the sequence number of the given elements in the sequence one by one. 

When we want the corresponding index of elements while iterating, we can use the ndenumerate() method. This method returns an iterator yielding pairs of array coordinates and values. It is multidimensional index iterator.

Example:

For 1-D Array:

import numpy as np
a=np.array(['a','b','c'])
for index, x in np.ndenumerate(a):
    print(index, x)

Output:

(0,) a
(1,) b
(2,) c

For 2-D Array:

import numpy as np
a=np.array([['a','b','c'],['d','e','f']])
for index, x in np.ndenumerate(a):
    print(index, x)

Output:

(0, 0) a
(0, 1) b
(0, 2) c
(1, 0) d
(1, 1) e
(1, 2) f