intermediate

Array Operations

6 min readLast updated: 2026-07-12

Overview

Learn how to access, slice, reshape, and broadcast elements inside NumPy arrays.

Learning Objectives

  • Slice and index 1D and 2D arrays.
  • Reshape and flatten arrays without copying data.
  • Understand the basics of array broadcasting.

Concept Explanation

Indexing and slicing in NumPy are similar to Python lists but work across multiple dimensions using commas. Slicing returns a 'view' of the array rather than a copy. Reshaping changes the dimensions of an array without changing its data. Broadcasting allows mathematical operations on arrays of different shapes.

Code Examples

Example 1 — Basics

This example introduces the fundamental syntax and concepts.

python
import numpy as np
arr = np.array([10, 20, 30, 40])
print(arr[1:3]) # Slice elements [20, 30]

Example 2 — Everyday Usage

This example demonstrates a realistic scenario handling business parameters.

python
# Reshape a flat array of 6 elements into a 2x3 matrix
flat_data = np.array([1, 2, 3, 4, 5, 6])
matrix = flat_data.reshape(2, 3)
print('Matrix:\n', matrix)
print('Flattened back:', matrix.flatten())

Example 3 — Practical Data Engineering Example

This example shows clean, production-grade code structure following senior development standards.

python
# Simple broadcasting: Add a single row offset to all rows in a matrix
matrix = np.array([
    [1, 2, 3],
    [4, 5, 6]
])
row_offset = np.array([10, 20, 30])
# Broadcasting duplicates row_offset array shape concept behind the scenes
adjusted_matrix = matrix + row_offset
print(adjusted_matrix)

Visual Flow

The following execution flow represents the step-by-step evaluation inside the interpreter:

text
1D Array (6 elements) → Change Shape Pointers → 2D Array (2x3 matrix) → Share same memory block

Common Mistakes

Review these common pitfalls when working with this topic:

  • Modifying a slice and forgetting it updates the original array (slices are views, not copies).
  • Reshaping to dimensions that do not match the total size of the original array (raises ValueError).
  • Broadcasting incompatible shapes without matching rules.
  • Using loops to slice matrix columns manually.

Best Practices

Enforce these Pythonic best practices in your codebase:

❌ Don't
python
sub_arr = arr[1:3]
# Expecting changes to sub_arr to leave original arr untouched
✅ Do
python
sub_arr = arr[1:3].copy() # Explicit copy to prevent side-effects

Performance Notes

Keep these optimization guidelines in mind for performance-sensitive hotpaths:

  • Slicing and reshaping return views, which saves memory by sharing the same database buffer.

Quick Revision

Use these key summaries for last-minute revision:

  • Index dimensions using comma separations: arr[row, col].
  • Slicing creates a view; modify slices carefully.
  • reshape() changes dimensions without copying data.
  • flatten() converts multi-dimensional arrays to 1D.
  • Broadcasting computes operations across different shapes automatically.