Skip to main content

NumPy: Iterating Array with different step size

This method is used for iterating when we want to do iterations of a particular part of the given array. This method can iterate the first,  last elements or every other element present in the array. Python has strong indexing built-in capabilities. Thus, here we can perform slicing with iteration to get the particular part of the array.

Example - 1:

import numpy as np
a=np.array([['a','b','c'],['d','e','f'],['g','h','i'],['j','k','l']])
#When we take 3 steps
for x in np.nditer(a[:,::3]):
    print(x)

Output:

a
d
g
j

Example - 2:

import numpy as np
a=np.array([['a','b','c'],['d','e','f'],['g','h','i'],['j','k','l']])
#When we take 2 steps
for y in np.nditer(a[:,::2]):
    print(y)

Output:

a
c
d
f
g
i
j
l
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.