This is an archived version of the course. Please see the latest version of the course.

Arithmetic operations

In basic Python, if you have two lists, and you want to add up the elements across both lists, you will need to use a loop.

x = [1, 2, 3]
y = [4, 5, 6]
z = []
for (i, j) in zip(x, y):
   z.append(i + j)
print(z)   ## [5, 7, 9]

In Numpy, you can easily perform such element-wise operations more efficiently and more compactly. No loops required! This process is called vectorisation (or a vectorised operation).

x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
z = x + y
print(z)   ## [5 7 9]

Here are some examples:

x = np.array([1, 2, 3, 4])
y = np.array([0, 1, 2, 3])
print(x + 2)     ## [3 4 5 6]
print(x - y)     ## [1 1 1 1]
print(x < 3)     ## [ True  True False False]
print(x + y > 5) ## [False False False  True]

a = np.array([[1,2], [3,4]])
b = np.array([[2,3], [4,5]])

# multiplying an array with a scalar
print(a * 3)         
## [[ 3  6]
##  [ 9 12]]

# elementwise multiplication
print(a * b)         
## [[ 2  6]
##  [12 20]]

# elementwise division
c = np.array([1, 2])
d = np.array([3, 4])
print(c / d)
## [0.33333333 0.5       ]

Matrix multiplication can be performed using the @ operator or np.matmul(). Make sure you note the difference between a*b and a@b!

print(a@b)
## [[10 13]
##  [22 29]]

print(np.matmul(a, b))
## [[10 13]
##  [22 29]]

To compute the inner product of two vectors (1D arrays), use np.dot() (dot product).

x = np.array([1, 2, 3])
y = np.array([2, 3, 4])
print(np.dot(x, y))  ## 20  == (1*2)+(2*3)+(3*4)