Skip to content

Array Slicing

Array Slicing

Multiple values stored within an array can be accessed simultaneously with array slicing. To pull out a section or slice of an array, the colon operator : is used when calling the index. The general form is:

<slice> = <array>[start:stop]

Where <slice> is the slice or section of the array object <array>. The index of the slice is specified in [start:stop]. Remember Python counting starts at 0 and ends at n-1. The index [0:2] pulls the first two values out of an array. The index [1:3] pulls the second and third values out of an array.

An example of array slicing the first two elements out of an array is below.

In [1]:
import numpy as np

a = np.array([2, 4, 6]) b = a[0:2] print(b)

[2 4]

A blank stands in for the last index. The slicing operation [1:] pulls out the 2nd through the last values of an array.
In [2]:
import numpy as np

a = np.array([2, 4, 6, 8]) b = a[1:] print(b)

[4 6 8]

A blank also stands in for the first index. The slicing operation [:3] pulls out the first through third values of an array.
In [3]:
import numpy as np

a = np.array([2, 4, 6, 8]) b = a[:3] print(b)

[2 4 6]

Slicing 2D Arrays

2D NumPy arrays can be sliced with the general form:

<slice> = <array>[start_row:end_row, start_col:end_col]

The code section below creates a two row by four column array and indexes out the first two rows and the first three columns.

In [4]:
import numpy as np

a = np.array([[2, 4, 6, 8], [10, 20, 30, 40]]) b = a[0:2, 0:3] print(b)

[[ 2  4  6]
 [10 20 30]]

Again, a blank represents the first index or the last index. The colon operator also represents "all".

The code section below slices out the first two rows and all columns from array a.

In [5]:
import numpy as np

a = np.array([[2, 4, 6, 8], [10, 20, 30, 40]]) b = a[:2, :] #[first two rows, all columns] print(b)

[[ 2  4  6  8]
 [10 20 30 40]]