This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 3: Array operations

Mathematical operations

face Josiah Wang

Let’s look at more examples of vectorisation.

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]

You can also use list comprehension to improve its speed and readability.

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

In NumPy, it’s even simpler. You just add up the two np.arrays! This is another example of vectorisation in action.

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

You can also use np.add(x, y) to achieve the same thing.

You can also add a scalar to a np.array and subtract a scalar from a np.array. The operation will be applied to each element in the np.array.

>>> x = np.array([1, 2, 3])
>>> y = x - 2
>>> print(y)
[-1  0  1]

You can also use np.subtract(x, 2) to achieve the same effect.

You can also use augmented assignment operators like += and -= as in pure Python.

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