A Soft Introduction to Numpy Arrays- Part 2: Slicing & Arithmetic Operations

K. N
4 min readDec 10, 2022

This article can be considered a continuation of part 1.

(Image source)

Slicing of Numpy Arrays:

Slicing in NumPy works similarly to slicing in Python’s built-in lists, but has some additional features that can be useful. The general syntax for slicing a NumPy array is a[start:stop:step, start:stop:step, ...], where a is the array you want to slice, and start, stop, and step are the slicing parameters that specify the starting and ending indices, as well as the step size for each dimension.

Let’s look at this example:

import numpy as np

# Create a rank-2 array with shape (3, 4)
# [[ 1 2 3 4]
# [ 5 6 7 8]
# [ 9 10 11 12]]
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

# Use slicing to extract a subarray with shape (2, 2), starting at index (1, 1)
# [[6 7]
# [10 11]]
b = a[1:3, 1:3]

In this example, we create a rank-2 array with shape (3, 4), and then use slicing to extract a subarray with shape (2, 2), starting at index (1, 1).

The above example shows slicing of a two dimensional array. Following example shows a 3-dimensional array being sliced:

import numpy as np

# Create a rank-3 array with shape (2, 3, 4)
# [[[ 1 2 3 4]
# [ 5 6 7 8]
# [ 9 10 11 12]]
#
# [[13…

--

--