Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 49 ยท Indexing and Selection

Indexing and Slicing

Select elements and sub-arrays in NumPy with positive and negative indexes, slices with steps, a[i, j] on 2D arrays, ellipsis and newaxis. Slices are views.

Picking out parts of an array is something you will do on every NumPy project. The syntax looks like Python list indexing, with two important upgrades: you can index several axes at once with a[i, j], and a slice returns a view of the original data instead of a copy.

This lesson covers single elements, slices with steps, rows and columns of 2D arrays, the ... (Ellipsis) shortcut, np.newaxis for adding dimensions, and the view behavior that catches many beginners by surprise. Later lessons build on this: Boolean Masks, Fancy Indexing and Views vs Copies.

One-dimensional indexing

Indexes start at 0, and negative indexes count from the end, exactly as in Python lists.

Python Indexes and slices on a 1D array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A slice is written start:stop:step. Every part is optional. The stop index is excluded, which means a[2:5] has 5 - 2 = 3 elements. A negative step walks backwards.

graph LR
    A0["10<br/>index 0 or -5"] --- A1["20<br/>index 1 or -4"] --- A2["30<br/>index 2 or -3"] --- A3["40<br/>index 3 or -2"] --- A4["50<br/>index 4 or -1"]

Every element has two valid indexes: counting from the start and counting from the end.

Unlike a plain a[10], which raises IndexError when it is out of range, slices are forgiving: a[5:100] just stops at the end of the array.

Two-dimensional indexing: a[i, j]

For a 2D array you give one index per axis, separated by a comma: row first, then column. This is cleaner and faster than the list-of-lists style a[i][j], which creates an intermediate row array.

Python Rows, columns and blocks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The colon : means "all of this axis". So m[:, 1] reads "every row, column 1" and m[0] is shorthand for m[0, :].

A key shape rule: an integer index removes that axis, while a slice keeps it. So m[:, 1] has shape (4,), but m[:, 1:2] has shape (4, 1). That difference matters for broadcasting, which you will meet in Broadcasting.

Python Integer versus slice shapes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A single element comes back as a NumPy scalar (such as numpy.int64) with shape (), not as an array.

Assigning into a slice

You can assign to an element or a whole region. A scalar fills the region; an array must have a compatible shape.

Python Assigning to slices

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In-place operators such as *= work on slices as well. The array's dtype stays the same, so assigning a float to an integer array truncates it.

Ellipsis and newaxis

With 3D or higher arrays, writing every colon gets tedious. The ellipsis ... stands for "as many colons as needed". It can appear once per index.

np.newaxis (an alias for None) inserts a new axis of length 1 at that spot. This is the standard tool for turning a 1D array into a row or column.

Python Ellipsis and newaxis

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line multiplies a column by a row and creates a full 3 by 3 table. That trick works because of broadcasting, the topic of an upcoming lesson.

Slices are views, not copies

This is the single most important fact about slicing. A basic slice does not copy data: it gives you a new array object that looks at the same memory. Changing the slice changes the original.

graph TD
    O["original array<br/>one block of memory"]
    O --> S["slice a[2:5]<br/>view into the same block"]
    S -. "writes go to the original" .-> O

A basic slice is a window onto the original data, so writes through the view are visible in the source.

Python A slice shares memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This is intentional: no copying means huge arrays can be sliced for free. When you want an independent array, call .copy(). The reverse rule also matters: a slice of a slice is still a view of the original. Views vs Copies explains which operations copy and which do not.

Warning: Python lists copy on slicing; NumPy arrays do not. Code like b = a[:3]; b[0] = 0 changes a too.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. For a = np.arange(10), what is a[2:8:3]?

    Start at 2, step by 3 and stop before 8: 2 and 5. The value 8 is excluded because stop is excluded.
  2. 2. m is a 4 x 4 array. What is the shape of m[:, 1:2]?

    The slice 1:2 keeps the column axis (length 1), so the shape is (4, 1). m[:, 1] with an integer would be (4,).
  3. 3. What does b = a[:3]; b[0] = 100 do to a?

    Basic slices are views on the same memory. Use a[:3].copy() for an independent array.
  4. 4. What does v[:, np.newaxis] do to a 1D array of length 3?

    np.newaxis inserts an axis of length 1 where it appears; placed after the colon it creates a column.

Summary

  • Indexes start at 0, negatives count from the end, and slices are start:stop:step with stop excluded.
  • Use a[i, j] for 2D arrays; : means a whole axis, an integer removes an axis, a slice keeps it.
  • ... fills in any number of colons; np.newaxis (or None) adds an axis of length 1.
  • Basic slices are views: writing through them changes the original, so use .copy() when you need independence.

Next: Boolean Masks and Filtering