Skip to main content

NumPy: Enumerated Iteration Using ndenumerate()

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
Submitted by devanshi.srivastava on September 9, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.