Slicing

Slicing consists three components, start:end:step. By default, start is , end is last and step is .

a = np.arange(10)
 
a[1:]
# array([1, 2, 3, 4, 5, 6, 7, 8, 9])
 
a[:3]
# array([0, 1, 2]), last index is not included.
 
a[::2]
#  array([0, 2, 4, 6, 8]), element at each 2 step

Advance Slicing

Slicing on multi-dimensional is bit tricky but useful. Following image is a better example to understand slicing on n-dimensional arrays.

Numpy slicing

Slice Assignment

Assignment can be done to array slices.

a[:8] = 10
# a becomes  array([10, 10, 10, 10, 10, 10, 10, 10,  8,  9])

References

  1. https://lectures.scientific-python.org/intro/numpy/array_object.html#indexing-and-slicing