NumPy Array Slicing

Slicing an array

In Python, slicing means taking elements from one given index to another given index.

We pass a slice instead of an index like this:[start:end].

We can also define a step length, as shown below:[start:end:step].

If we do not pass startis considered as 0.

If we do not pass endis considered as the length of the array within the dimension.

If we do not pass stepis considered as 1.

Example

Cut the elements from index 1 to index 5 of the following array:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5])

Run Instance

Note:The result includes the starting index but not the ending index.

Example

Slice elements from index 4 to the end of the array:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[4:])

Run Instance

Example

Slice elements from the beginning to index 4 (excluding):

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[:4])

Run Instance

Negative Slicing

Use the minus operator to reference indices from the end:

Example

Slice the array from index 3 starting from the end to index 1 starting from the end:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[-3:-1])

Run Instance

STEP

Please use the step value to determine the slicing step:

Example

Return elements at intervals from index 1 to index 5:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5:2])

Run Instance

Example

Return elements at intervals in the array:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[::2])

Run Instance

Slicing 2-D Arrays

Example

Slice elements from index 1 to index 4 (excluding) starting from the second element:

import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[1, 1:4])

Run Instance

Note:Remember that the index of the second element is 1.

Example

Return index 2 from two elements:

import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 2])

Run Instance

Example

Slice indices 1 to 4 (excluding) from two elements, which will return a 2-D array:

import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 1:4])

Run Instance