Indexing and Slicing in NumPy

NumPy arrays support powerful and flexible ways to access and manipulate data using indexing and slicing. These techniques allow you to extract individual elements, subsets of arrays, or even reshape and modify data efficiently.

Understanding how to access parts of an array is essential for working with numerical data. Whether you're analyzing datasets, processing images, or building machine learning models, NumPy's indexing and slicing features are foundational tools.

  • Indexing: Access individual elements using their position in the array.
  • Slicing: Extract subarrays using range-based syntax.


Indexing in NumPy

Indexing in NumPy allows you to access individual elements in an array by their position. NumPy uses zero-based indexing, which means the first element is at index 0.

Let’s look at how indexing works with 1D and 2D arrays.

1D Array Indexing

For a one-dimensional array, you can access elements using square brackets and the index number:

python
import numpy as np

arr = np.array([10, 20, 30, 40, 50])

print(arr[0])   # 10 (first element)
print(arr[2])   # 30 (third element)
print(arr[-1])  # 50 (last element)

How It Works:

  • arr[0]: Gets the first element.
  • arr[2]: Gets the third element.
  • arr[-1]: Gets the last element (negative indexing).

Output

10
30
50

2D Array Indexing

For two-dimensional arrays, use a pair of indices — one for the row and one for the column:

python
arr_2d = np.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
])

print(arr_2d[0, 0])  # 1 (first row, first column)
print(arr_2d[1, 2])  # 6 (second row, third column)
print(arr_2d[2, -1]) # 9 (third row, last column)

How It Works:

  • arr_2d[0, 0]: First row, first column.
  • arr_2d[1, 2]: Second row, third column.
  • arr_2d[2, -1]: Third row, last column.

Output

1
6
9

💡 Tip: You can also use slicing with indexing to extract parts of the array — we’ll explore that next!


Slicing in NumPy

Slicing lets you extract a portion of a NumPy array using a range of indices. The basic slicing syntax is similar to Python lists:start:stop. NumPy slicing is fast and memory-efficient because it returns a view of the original array whenever possible.

You can also add a third value, step, to define the interval between indices: start:stop:step.

1D Array Slicing

Here's how to slice a one-dimensional array:

python
import numpy as np

arr = np.array([10, 20, 30, 40, 50, 60])

print(arr[1:4])    # [20 30 40]
print(arr[:3])     # [10 20 30]
print(arr[3:])     # [40 50 60]
print(arr[::2])    # [10 30 50] (every second element)
print(arr[-3:-1])  # [40 50]

How It Works:

  • arr[1:4]: Elements from index 1 to 3 (stop is exclusive).
  • arr[:3]: First three elements.
  • arr[3:]: Elements from index 3 to the end.
  • arr[::2]: Every second element.
  • arr[-3:-1]: Slices using negative indices.

Output

[20 30 40]
[10 20 30]
[40 50 60]
[10 30 50]
[40 50]

2D Array Slicing

You can slice both rows and columns in a 2D array by using a comma to separate the dimensions: array[row_slice, column_slice].

python
arr_2d = np.array([
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
])

print(arr_2d[0:2, 1:3])  # rows 0-1, columns 1-2
print(arr_2d[:, 2])      # all rows, column 2
print(arr_2d[1, :])      # row 1, all columns

How It Works:

  • arr_2d[0:2, 1:3]: Subarray from rows 0–1 and columns 1–2.
  • arr_2d[:, 2]: All rows, third column.
  • arr_2d[1, :]: Second row, all columns.

Output

[[2 3]
 [6 7]]
[ 3  7 11]
[5 6 7 8]

💡 Tip: Slicing returns a *view* of the original array (not a copy). Modifying the sliced array will affect the original unless you explicitly use .copy().


Example 1: Basic Indexing and Slicing

Let’s say you have an array representing scores of a student in six subjects. You want to:

  • Access the first and last scores.
  • Get all scores except the first one.
  • Extract every second score.
python
import numpy as np

scores = np.array([75, 45, 86, 53, 48, 64])

# First and last score
print("First score:", scores[0])
print("Last score:", scores[-1])

# All scores except the first one
print("Except first:", scores[1:])

# Every second score
print("Every second:", scores[::2])

How It Works:

  • scores[0]: Gets the first element in the array.
  • scores[-1]: Gets the last element using negative indexing.
  • scores[1:]: Returns all elements starting from index 1 to the end.
  • scores[::2]: Returns every second element, starting from index 0.

Output

First score: 75
Last score: 64
Except first: [45 86 53 48 64]
Every second: [75 86 48]

This example combines basic indexing (like scores[0]) and slicing (like scores[1:] and scores[::2]) to extract specific data from a NumPy array.

💡 Tip: Slicing does not include the end index, and it can be used with steps to skip values.


Example 2: Slicing a 2D Array

Suppose you have a 3×4 matrix representing sales data where each row is a region and each column is a quarter (Q1 to Q4). You want to:

  • Get sales data for the first two regions.
  • Extract Q2 and Q3 data for all regions.
  • Get all quarters for the second region.
python
import numpy as np

sales = np.array([
    [250, 270, 260, 280],  # Region 1
    [300, 310, 305, 315],  # Region 2
    [220, 230, 225, 235]   # Region 3
])

# First two regions (rows 0 and 1)
print("sales[0:2, :] :")
print(sales[0:2, :])

# Q2 and Q3 for all regions (columns 1 and 2)
print("sales[:, 1:3] :")
print(sales[:, 1:3])

# All quarters for Region 2 (row 1)
print("sales[1, :] :")
print(sales[1, :])

How It Works:

  • sales[0:2, :]: Selects rows 0 and 1 (first two regions), all columns.
  • sales[:, 1:3]: Selects columns 1 and 2 (Q2 and Q3), all rows.
  • sales[1, :]: Selects row 1 (Region 2), all columns.

Output

[[250 270 260 280]
 [300 310 305 315]]
[[270 260]
 [310 305]
 [230 225]]
[300 310 305 315]

💡 Tip: Use : to select all rows or all columns in a dimension.


Frequently Asked Questions

What is indexing in NumPy?

Indexing in NumPy refers to accessing individual elements of an array using their position. NumPy uses zero-based indexing.


What is slicing in NumPy?

Slicing allows you to extract a portion of a NumPy array using a start:stop or start:stop:step format.


What is the difference between indexing and slicing?

Indexing accesses a single element, while slicing retrieves a subarray. Slicing can return views; indexing returns a value.


Can I use negative indices in NumPy?

Yes, NumPy supports negative indexing. For example, arr[-1] gives the last element of the array.


Does slicing return a view or a copy?

Slicing typically returns a view of the array, not a copy. Changes to the slice will affect the original array unless you use .copy().



What's Next?

In the next section, we’ll dive deeper into Fancy and Boolean Indexing — powerful techniques that allow you to select elements using arrays of indices or conditional logic.

These methods go beyond basic slicing, giving you fine-grained control over how data is accessed and manipulated in NumPy arrays.