py4u blog

Mastering `numpy.put()` in Python: A Comprehensive Guide

NumPy is the cornerstone of numerical computing in Python, enabling efficient array operations. The numpy.put() function is a versatile tool for modifying array elements by specifying indices and corresponding values. Unlike direct indexing (e.g., arr[indices] = values), numpy.put() operates on the flattened array (treating multi-dimensional arrays as 1D), making it ideal for bulk updates with arbitrary indices. This guide explores its syntax, use cases, best practices, and pitfalls.

2026-10

Table of Contents#

Syntax of numpy.put()#

The syntax for numpy.put() is:

numpy.put(a, ind, v, mode='raise')

Parameters in Detail#

Input Array (a)#

  • The array to modify (modified in place).
  • Can be a NumPy array or array-like (converted to a NumPy array internally).

Indices (ind)#

  • Array-like of integers specifying the (flattened) indices where values from v will be placed.
  • If ind is a scalar, it is treated as a single index.
  • Indices refer to the flattened array (e.g., a 2D array [[1,2],[3,4]] has flattened indices 0,1,2,3).

Values (v)#

  • Array-like of values to place into a at the indices ind.
  • If v is shorter than ind, it is repeated to match the length of ind (e.g., v=5 and ind=[0,1,2] assigns 5 to all three indices).

Mode (mode)#

  • Controls how out-of-bounds indices are handled (optional, default: 'raise'):
    • 'raise': Raise an error if any index is out of bounds.
    • 'wrap': Wrap out-of-bounds indices (e.g., index 5 in a length-5 array becomes 0).
    • 'clip': Clip out-of-bounds indices to the valid range (e.g., index -1 becomes 0, index 5 becomes 4 for a length-5 array).

Return Value#

numpy.put() modifies the array in place and returns None (no new array is created).

Examples of numpy.put()#

Basic Usage#

Modify a 1D array at a single index:

import numpy as np
 
arr = np.array([10, 20, 30, 40, 50])
np.put(arr, 2, 99)  # Place 99 at index 2 (flattened)
print(arr)  # Output: [10, 20, 99, 40, 50]

For a 2D array (flattened indices):

arr_2d = np.array([[1, 2], [3, 4], [5, 6]])
# Flattened indices: 0→1, 1→2, 2→3, 3→4, 4→5, 5→6
np.put(arr_2d, [1, 3], [99, 100])
print(arr_2d)  # Output: [[  1,  99], [  3, 100], [  5,   6]]

Using mode='wrap'#

Wrap out-of-bounds indices:

arr = np.array([1, 2, 3, 4, 5])
np.put(arr, [5, 6], [9, 10], mode='wrap')
# 5 % 5 = 0, 6 % 5 = 1 → assign 9 to 0, 10 to 1
print(arr)  # Output: [9, 10, 3, 4, 5]

Using mode='clip'#

Clip out-of-bounds indices to the valid range:

arr = np.array([1, 2, 3, 4, 5])
np.put(arr, [-1, 5], [9, 10], mode='clip')
# -1 clips to 0, 5 clips to 4 (len(arr)-1 = 4)
print(arr)  # Output: [9, 2, 3, 4, 10]

Multiple Indices and Values#

Update multiple indices with corresponding values:

arr = np.array([10, 20, 30, 40, 50, 60])
indices = [1, 3, 5]
values = [22, 44, 66]
np.put(arr, indices, values)
print(arr)  # Output: [10, 22, 30, 44, 50, 66]

Common Use Cases#

  • Bulk Updates: Modify specific elements when you have a list of indices (e.g., from np.argwhere() or a precomputed mapping).
  • Flattened Array Manipulation: Work with multi-dimensional arrays as flattened 1D arrays (e.g., image processing with flattened pixel indices).
  • Index Mapping: Update elements based on external index mappings (e.g., in simulations where particle indices map to array positions).

Best Practices#

  1. Flattened Indices Awareness: Remember put() works on the flattened array. For multi-dimensional indexing, use numpy.put_along_axis() or direct indexing.
  2. Preserve Original Arrays: Make a copy of the array before using put() if you need to keep the original unchanged:
    original = np.array([1,2,3])
    modified = original.copy()
    np.put(modified, 1, 99)
  3. Mode Parameter: Use mode='raise' (default) during development to catch index errors. Switch to 'wrap'/'clip' only if out-of-bounds indices are expected.
  4. Efficiency: For sequential indices (slices), direct indexing (e.g., arr[0:3] = 5) is faster. Use put() for non-sequential indices.

Potential Pitfalls#

  1. Flattened Indices Misunderstanding: Accidentally modifying the wrong elements in multi-dimensional arrays (e.g., a 2D array’s index 5 may not be where you expect).
  2. Out-of-Bounds Indices: Forgetting to handle out-of-bounds indices leads to errors (with mode='raise') or unexpected values (with mode='wrap'/'clip').
  3. In-Place Modification: Accidentally modifying the original array when a copy was intended.
  4. Broadcasting Issues: Ensure v is compatible with ind (e.g., v’s length matches ind or can be repeated to match).

Conclusion#

numpy.put() is a powerful tool for modifying array elements at specific (flattened) indices. By mastering its parameters (especially mode) and following best practices (e.g., using copies for immutability), you can efficiently update arrays in bulk. Remember its behavior with multi-dimensional arrays (flattened indices) and choose the right tool (e.g., put_along_axis() for multi-dimensional indexing) when needed.

References#