Python

Indexing, Slicing & Iteration

Learn how to access, modify, and navigate through NumPy arrays of any dimension.

By TechCoder TeamLast updated: 2026-06-02
In a Nutshell

Learn how to access, modify, and navigate through NumPy arrays of any dimension. This hands-on tutorial focuses on practical implementation of indexing, slicing & iteration concepts.

Module 3: Indexing, Slicing & Iteration

Getting data into arrays is step one. Step two is getting data out of them or modifying specific parts. NumPy indexing is similar to Python list indexing but extends into multiple dimensions.


Lesson 5: Indexing Basics

1D Indexing

Identical to Python lists. Indexes start at 0.

arr = np.array([10, 20, 30])
print(arr[1]) # 20

2D and 3D Indexing

In multi-dimensional arrays, you use a comma-separated tuple of indexes.

  • 2D: arr[row, col]
  • 3D: arr[depth, row, col]

Negative Indexing

You can use negative numbers to count from the end (-1 is the last element).

PYTHON PLAYGROUND
⏳ Loading editor…

Lesson 6: Slicing Techniques

Slicing allows you to extract a sub-portion of an array. The syntax is [start:stop:step].

Multi-Dimensional Slicing

You can slice each dimension independently. matrix[0:2, 1:3] extracts rows 0 to 1, and columns 1 to 2.

CRITICAL: Views vs Copies

In Python lists, a slice creates a copy. In NumPy, a slice creates a view! If you modify a slice, you modify the original array. To create a separate array, use .copy().

PYTHON PLAYGROUND
⏳ Loading editor…

Lesson 7: Iteration

While looping with for is possible, it is usually avoided in NumPy because it's slow. Always try to use "Vectorized Operations" (covered in next module).

If you must loop:

  • nditer(): A sophisticated multi-dimensional iterator object.
  • .flat: A property that returns a 1D iterator over the entire array.
PYTHON PLAYGROUND
⏳ Loading editor…

Practice: Image Matrix Slicing

Think of a 2D array as a grayscale image. Challenge: Given a 10x10 array of zeros, can you slice the inner 4x4 square (indexes 3 to 7) and set it to 1s?

Quiz

Question 1 of 5

What happens to the original array if you modify a slice of it?

Nothing, slices are copies
The original array is also modified
The slice becomes its own object and detaches
It throws an error

Key Takeaways

✅ Access elements using [row, col] syntax.
Slices are views, not copies.
✅ Avoid for loops where possible; let NumPy handle it.