Reference Manual • Chapter 4

Arrays & NumPy Array Processing

An authoritative reference manual on native Python array module vs NumPy ndarrays, C-contiguous memory layouts, strides, SIMD vectorization, aliasing vs view vs copy, basic slicing, advanced fancy indexing, boolean masks, and attributes.

Array processing forms the foundation of high-performance numerical computing. This chapter contrasts native Python arrays against multidimensional NumPy arrays, detailing SIMD vectorization, memory strides, aliasing, basic slicing, advanced fancy indexing, boolean masking, and array attributes.

4.1. 1. Native Python Array Module vs NumPy Arrays

Definition: The native `array` module manages 1D homogeneous primitive values; `NumPy` provides N-dimensional C-contiguous array structures (`ndarray`) optimized for vectorized SIMD math operations.

Core Working Principles:

Feature Dimension Python Lists Native array Module NumPy ndarray 🏆
Data Homogeneity Heterogeneous (mixed data types) Homogeneous (single primitive type) Homogeneous (single data type)
Dimensionality 1D (Nested lists for multi-D) 1D only Arbitrary N-Dimensions
Math Execution Python loops (Slow $O(N)$ overhead) Python loops (Moderate) Vectorized C-speed SIMD broadcasting
5-Marks Exam Scoring Points
  • NumPy ndarrays execute math at C speed via SIMD vectorization.
  • b = a creates an alias pointer; b = a.copy() creates a deep memory copy.
  • Native array module is limited to 1D primitive values.

4.2. 2. NumPy Slicing, Advanced Indexing & Attributes

Definition: NumPy arrays support basic slicing, advanced integer/boolean indexing, and multidimensional shape manipulation.

Core Working Principles:

graph TD
    Arr[2D NumPy Array Shape 3x3] --> Attr[Attributes: ndim=2, shape=3,3, size=9]
    Arr --> BasicSlice[Basic Slicing: arr 0:2, 1:3 -> Returns View]
    Arr --> FancyIndex[Fancy Indexing: arr 0, 2 -> Returns Copy]
    Arr --> BoolIndex[Boolean Indexing: arr arr > 50 -> Returns 1D Filtered Copy]
                    
Architecture Specification 4.1: NumPy Array Indexing & Slicing Memory Paradigms
import numpy as np

# Create 2D NumPy Array
matrix = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])

# Attributes
print(f"Dimensions: {matrix.ndim} | Shape: {matrix.shape} | Size: {matrix.size} | Dtype: {matrix.dtype}")

# 1. Basic Slicing (Rows 0-1, Cols 1-2) -> Returns View
view_slice = matrix[0:2, 1:3]

# 2. Fancy Integer Indexing (Select Rows 0 and 2) -> Returns Copy
row_copy = matrix[[0, 2]]

# 3. Boolean Mask Indexing (Elements > 45) -> Returns Copy
mask_copy = matrix[matrix > 45]

print("Boolean Filtered Result (>45):", mask_copy)
5-Marks Exam Scoring Points
  • Basic slicing returns a View; modifying values in a view mutates the original array.
  • Advanced indexing (integer array / boolean mask) allocates a brand-new Copy.
  • Array shape can be reshaped using reshape(rows, cols).

✍️ Chapter 4 Reference Exercises & Review Problems

Exercise 4.1: Contrast Basic Array Slicing against Advanced Fancy Indexing in NumPy regarding memory allocation.
Step-by-Step Reference Solution:
- **Basic Slicing (`arr[0:2, 1:3]`):** Generates a **View** sharing original memory. No new memory buffer is allocated; altering view data directly mutates the source array!
- **Advanced Indexing (`arr[[0, 2]]` or `arr[arr > 5]`):** Generates an independent **Copy** in new memory. Modifying elements in the copied array does NOT affect the source array.
Exercise 4.2: Given a 2D NumPy array `arr = np.arange(1, 10).reshape(3, 3)`, write code to extract (a) the middle row, (b) the last column, and (c) all elements greater than 5.
Step-by-Step Reference Solution:
import numpy as np
arr = np.arange(1, 10).reshape(3, 3)

# (a) Middle Row (index 1)
middle_row = arr[1, :]  # Output: [4, 5, 6]

# (b) Last Column (index -1)
last_col = arr[:, -1]   # Output: [3, 6, 9]

# (c) Elements greater than 5
gt_five = arr[arr > 5]   # Output: [6, 7, 8, 9]