Access Elements of Array - Numpy
NumPy - Access elements of array
To access elements of a numpy array, you can use indexing operator []
.
The indexing operator takes an integer or a list of integers representing the indices of elements you want to access.
index starts with a value of 0 for first element, and increments by one for subsequent elements.
If arr is numpy array, then the following expression accesses the element at index=5.
arr[5]
If arr is numpy array, then the following expression accesses the elements from start index of 5 to a stop index of 10 (stop not included in the returned object).
arr[5:10]
We can also specify a step value, with the following syntax.
arr[start:stop:step]
If the array is multi-dimensional then we can specify the indices for as many dimensions as required.
arr[index_1][index_2]
Accessing a range of elements is called slicing, and please refer the tutorial - NumPy Array Slicing.
Examples
1. Access element at index=5
In the following program, we take a numpy array (one dimensional), and access the element at index=5.
Python Program
import numpy as np
arr = np.array([1, 2, 4, 9, 16, 25, 36, 49, 64])
element = arr[5]
print(element)
Output
25
Explanation
[1, 2, 4, 9, 16, 25, 36, 49, 64] <- arr
0 1 2 3 4 5 6 7 8 <- indices
arr[5] is 25
2. Access elements from index=2 until index=6
In the following program, we take a numpy array (one dimensional), and access the elements from index=2 until index=6.
Python Program
import numpy as np
arr = np.array([1, 2, 4, 9, 16, 25, 36, 49, 64])
elements = arr[2:6]
print(elements)
Output
[ 4 9 16 25]
Explanation
[1, 2, 4, 9, 16, 25, 36, 49, 64] <- arr
0 1 2 3 4 5 6 7 8 <- indices
|--------------|
4, 9, 16, 25 <- arr[2:6]
3. Access elements from index=2 until index=8 in steps of 2
In the following program, we take a numpy array (one dimensional), and access the elements from index=2 until index=8 in steps of 2.
Python Program
import numpy as np
arr = np.array([1, 2, 4, 9, 16, 25, 36, 49, 64])
elements = arr[2:8:2]
print(elements)
Output
[ 4 16 36]
Explanation
[1, 2, 4, 9, 16, 25, 36, 49, 64] <- arr
0 1 2 3 4 5 6 7 8 <- indices
|- - - |
4, 16, 36 <- arr[2:8:2]
Summary
In this NumPy Tutorial, we learned how to access elements of a numpy array using indexing operator.