How to Index 1D NumPy Arrays?

Numpy is a popular Python library for data science focusing on arrays, vectors, and matrices.

Problem Formulation: Given a one-dimensional NumPy array arr.

  • How to access the i-th value in the array?
  • How to access all values between the i-th value (included) and the j-th value (excluded) from the array?
  • How to access all values between the i-th value (included) and the j-th value (excluded) from the array, using only every k-th element (step size)?

Method 1: Indexing — Access i-th Value

To access the i-th value of a NumPy array use the square bracket indexing notation array[i]. The first element has index 0, the second element has index 1, and the (i+1)-th element has index i.

import numpy as np

# The Fibonacci Series (1D Array)
arr = np.array([0, 1, 1, 2, 3, 5, 8])

# Access element with index i=2
print(arr[2])
# 1

# Access element with index i=5
print(arr[5])
# 5

# Access element with index i=0
print(arr[0])
# 0

Method 2: Slicing — Access Values Between i and j

To access all values between the i-th value (included) and the j-th value (excluded) use the square bracket slicing notation array[i:j].

import numpy as np

# The Fibonacci Series (1D Array)
arr = np.array([0, 1, 1, 2, 3, 5, 8])

# Access slice between i=2 and j=5
print(arr[2:5])
# [1 2 3]

# Access slice between i=0 and j=5
print(arr[:5])
# [0 1 1 2 3]

# Access slice between i=2 and j=3
print(arr[2:3])
# [1]

Method 3: Slicing with Step Size — Access Every k-th Value Between i and j

To access every k-th value between the i-th value (included) and the j-th value (excluded) use the square bracket slicing notation array[i:j:k].

import numpy as np

# The Fibonacci Series (1D Array)
arr = np.array([0, 1, 1, 2, 3, 5, 8])

# Access slice between i=2 and j=5 using step k=2
print(arr[2:5:2])
# [1 3]

# Access slice between i=0 and j=5 using step k=3
print(arr[:5:3])
# [0 2]

# Access slice between i=5 and j=1 using step k=-1
print(arr[5:1:-1])
# [5 3 2 1]

NumPy Puzzle Indexing & Slicing 1D Array

Python Puzzle 1D Slicing

This puzzle demonstrates indexing in NumPy arrays. You most likely know indexing for Python lists or strings. Indexing for numpy works in a similar way.

There are two interesting twists in this puzzle. First, we overwrite each third value of the array with the concise expression F[::3] starting from the very first entry. Second, we print the sum of the first four values. As we have just overwritten the first and the fourth value, the sum is only 2.

What is the output of this puzzle?
*Intermediate Level*


Are you a master coder?
Test your skills now!