Curriculum
Course: NumPy
Login

Curriculum

NumPy

Text lesson

Iterating With Different Step Size

We can apply filtering and then proceed with iteration.

Example

Iterate through each scalar element of the 2-D array, skipping every other element:

import numpy as np

arr = np.array([[1234], [5678]])

for x in np.nditer(arr[:, ::2]):
  print(x)

Enumerated Iteration Using ndenumerate()

Enumeration refers to specifying the sequence number of items one by one.

In some cases, we need the corresponding index of each element during iteration; for these situations, the ndenumerate() method can be utilized.

Example

Enumerate the elements of the following 1-D array:

import numpy as np

arr = np.array([123])

for idx, x in np.ndenumerate(arr):
  print(idx, x)

Example

Enumerate the elements of the following 2-D array:

import numpy as np

arr = np.array([[1234], [5678]])

for idx, x in np.ndenumerate(arr):
  print(idx, x)