Skip to main content
Iterator objects for iterating over arrays in various ways.

Classes

nditer

Efficient multi-dimensional iterator

ndenumerate

Index and value iterator

ndindex

N-dimensional index iterator

flatiter

Flat iterator object

nditer

numpy.nditer(op, flags=None, op_flags=None, op_dtypes=None, order='K',
             casting='safe', op_axes=None, itershape=None, buffersize=0)
Efficient multi-dimensional iterator object to iterate over arrays.

Parameters

op
ndarray or sequence of array_like
The array(s) to iterate over.
flags
sequence of str
Flags to control the behavior of the iterator:
  • 'buffered': Enable buffering
  • 'c_index': Track flat C-order index
  • 'f_index': Track flat Fortran-order index
  • 'multi_index': Track multi-dimensional index
  • 'external_loop': Iterate in chunks for better performance
  • 'reduce_ok': Allow reduction operations
op_flags
list of list of str
Flags for each operand:
  • 'readonly': Operand is read-only
  • 'readwrite': Operand can be read and written
  • 'writeonly': Operand is write-only
  • 'allocate': Allocate output array
order
{'C', 'F', 'A', 'K'}
default:"'K'"
Control iteration order of indices.

Examples

import numpy as np

# Basic iteration
a = np.array([[1, 2], [3, 4]])
for x in np.nditer(a):
    print(x, end=' ')
# 1 2 3 4

# Iterate with multi-index
a = np.array([[1, 2], [3, 4]])
it = np.nditer(a, flags=['multi_index'])
for x in it:
    print(f"{it.multi_index}: {x}")
# (0, 0): 1
# (0, 1): 2
# (1, 0): 3
# (1, 1): 4

# Modify array elements
a = np.array([1, 2, 3, 4])
for x in np.nditer(a, op_flags=['readwrite']):
    x[...] = x * 2
print(a)
# [2 4 6 8]

# Iterate over multiple arrays
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
for x, y in np.nditer([a, b]):
    print(f"{x} * {y} = {x*y}")
# 1 * 4 = 4
# 2 * 5 = 10
# 3 * 6 = 18

# External loop for better performance
a = np.arange(6).reshape(2, 3)
for x in np.nditer(a, flags=['external_loop'], order='F'):
    print(x, end=' ')
# [0 3] [1 4] [2 5]

# Broadcasting iteration
a = np.array([[1, 2, 3]])
b = np.array([[4], [5], [6]])
for x, y in np.nditer([a, b]):
    print(f"{x} + {y} = {x+y}")
# 1 + 4 = 5
# 2 + 4 = 6
# 3 + 4 = 7
# 1 + 5 = 6
# 2 + 5 = 7
# 3 + 5 = 8
# 1 + 6 = 7
# 2 + 6 = 8
# 3 + 6 = 9

ndenumerate

numpy.ndenumerate(arr)
Multidimensional index iterator returning pairs of array coordinates and values.

Parameters

arr
ndarray
Input array.

Yields

index
tuple of ints
The current coordinates in the array.
value
scalar
The array element at the current coordinates.

Examples

import numpy as np

# 1D array
a = np.array([10, 20, 30])
for index, value in np.ndenumerate(a):
    print(f"a{index} = {value}")
# a(0,) = 10
# a(1,) = 20
# a(2,) = 30

# 2D array
a = np.array([[1, 2], [3, 4]])
for index, value in np.ndenumerate(a):
    print(f"a{index} = {value}")
# a(0, 0) = 1
# a(0, 1) = 2
# a(1, 0) = 3
# a(1, 1) = 4

# 3D array
a = np.arange(8).reshape(2, 2, 2)
for index, value in np.ndenumerate(a):
    if value > 3:
        print(f"a{index} = {value}")
# a(1, 0, 0) = 4
# a(1, 0, 1) = 5
# a(1, 1, 0) = 6
# a(1, 1, 1) = 7

# Modify values during iteration
a = np.array([[1, 2], [3, 4]])
for index, value in np.ndenumerate(a):
    a[index] = value * 10
print(a)
# [[10 20]
#  [30 40]]

# Build a dictionary from array
a = np.array([[1, 2], [3, 4]])
array_dict = {index: value for index, value in np.ndenumerate(a)}
print(array_dict)
# {(0, 0): 1, (0, 1): 2, (1, 0): 3, (1, 1): 4}

ndindex

numpy.ndindex(*shape)
An N-dimensional iterator object to index arrays.

Parameters

shape
ints, or a single tuple of ints
The size of each dimension of the array can be passed as individual parameters or as the elements of a tuple.

Yields

index
tuple of ints
Index tuples for an array of the given shape.

Examples

import numpy as np

# Dimensions as individual arguments
for index in np.ndindex(3, 2):
    print(index)
# (0, 0)
# (0, 1)
# (1, 0)
# (1, 1)
# (2, 0)
# (2, 1)

# Dimensions as a tuple
for index in np.ndindex((3, 2)):
    print(index)
# (0, 0)
# (0, 1)
# (1, 0)
# (1, 1)
# (2, 0)
# (2, 1)

# Use with arrays
a = np.zeros((3, 2))
for index in np.ndindex(a.shape):
    a[index] = sum(index)
print(a)
# [[0. 0.]
#  [1. 1.]
#  [2. 2.]]

# 3D iteration
for index in np.ndindex(2, 2, 2):
    print(index)
# (0, 0, 0)
# (0, 0, 1)
# (0, 1, 0)
# (0, 1, 1)
# (1, 0, 0)
# (1, 0, 1)
# (1, 1, 0)
# (1, 1, 1)

# Create index arrays
indices = list(np.ndindex(2, 3))
print(indices)
# [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]

# Initialize array with index-based values
a = np.zeros((3, 3))
for i, j in np.ndindex(3, 3):
    a[i, j] = i + j
print(a)
# [[0. 1. 2.]
#  [1. 2. 3.]
#  [2. 3. 4.]]

flatiter

numpy.flatiter
Flat iterator object to iterate over arrays as if they were 1-D.

Notes

A flatiter iterator is returned by the .flat attribute of an ndarray.

Attributes

coords
tuple of ints
An N-dimensional tuple of current coordinates.
index
int
Current flat index into the array.

Examples

import numpy as np

# Basic flat iteration
a = np.array([[1, 2], [3, 4]])
for item in a.flat:
    print(item, end=' ')
# 1 2 3 4

# Access by flat index
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.flat[0])  # 1
print(a.flat[3])  # 4
print(a.flat[-1])  # 6

# Get coordinates
a = np.array([[1, 2], [3, 4]])
it = a.flat
for item in it:
    print(f"Index: {it.index}, Coords: {it.coords}, Value: {item}")
# Index: 0, Coords: (0, 0), Value: 1
# Index: 1, Coords: (0, 1), Value: 2
# Index: 2, Coords: (1, 0), Value: 3
# Index: 3, Coords: (1, 1), Value: 4

# Modify via flat iterator
a = np.array([[1, 2], [3, 4]])
for i, item in enumerate(a.flat):
    a.flat[i] = item * 10
print(a)
# [[10 20]
#  [30 40]]

# Slice flat iterator
a = np.arange(12).reshape(3, 4)
print(a.flat[2:8])
# [2 3 4 5 6 7]

# Copy to flat array
a = np.array([[1, 2], [3, 4]])
flat_copy = np.array(a.flat)
print(flat_copy)
# [1 2 3 4]

Performance Comparison

import numpy as np
import time

a = np.random.rand(1000, 1000)

# Method 1: nditer (flexible but slower)
start = time.time()
result = 0
for x in np.nditer(a):
    result += x
print(f"nditer: {time.time() - start:.4f}s")

# Method 2: flat (faster for simple iteration)
start = time.time()
result = 0
for x in a.flat:
    result += x
print(f"flat: {time.time() - start:.4f}s")

# Method 3: Built-in operations (fastest)
start = time.time()
result = np.sum(a)
print(f"np.sum: {time.time() - start:.4f}s")

# Recommendation: Use built-in NumPy functions when possible

Notes

When to Use Each Iterator

  • nditer: Complex iteration patterns, multiple arrays, broadcasting
  • ndenumerate: Need both index and value, modifying specific elements
  • ndindex: Generating all possible indices for an array shape
  • flatiter: Simple 1D iteration over multidimensional array

Performance Tips

  1. Avoid explicit iteration when possible - use vectorized NumPy operations
  2. Use external_loop flag with nditer for better performance
  3. Use flat for simple iteration over all elements
  4. Pre-allocate output arrays when using iterators to modify arrays

Memory Efficiency

  • All iterators are memory-efficient and don’t create copies
  • nditer with buffering may use additional memory for optimization
  • Modifying arrays through iterators operates in-place

See Also

Build docs developers (and LLMs) love