# Python NumPy For Your Grandma - 2.6 Basic Math On Arrays

Contents

In this section, we’ll take a look at some basic math operations between arrays.

We’ll start by defining a pair of two by two arrays, `foo` and `bar`.

``````import numpy as np
foo = np.array([[4,3], [1,0]])
print(foo)
## [[4 3]
##  [1 0]]
``````
``````bar = np.array([[1,2], [3,4]])
print(foo)
## [[4 3]
##  [1 0]]
``````

If we add foo plus bar, watch what happens.

``````foo + bar
## array([[5, 5],
##        [4, 4]])
``````

The values of `foo` and `bar` get added element-wise. This pattern of element-wise addition holds true for every math operation between identically sized arrays.

For example, if we subtract `bar` from `foo`, it does element-wise subtraction.

``````foo - bar
## array([[ 3,  1],
##        [-2, -4]])
``````

If we multiply `foo` by `bar`, it does element-wise multiplication.

``````foo * bar
## array([[4, 6],
##        [3, 0]])
``````

And if we divide `foo` by `bar`, it does element-wise division.

``````foo / bar
## array([[4.        , 1.5       ],
##        [0.33333333, 0.        ]])
``````

Now, if you wanted to do matrix multiplication instead of element-wise multiplication, you can do that too using the @ symbol, like `foo @ bar`.

``````foo @ bar
## array([[13, 20],
##        [ 1,  2]])
``````

Now suppose we want to add a scalar like 5 to each element of `foo`. You might be inclined to build a 4x4 array array filled with 5s and then carry out the addition, which works, but it’s overkill.

``````foo + np.full(shape=foo.shape, fill_value=5)
## array([[9, 8],
##        [6, 5]])
``````

All you need to do in this case is `foo + 5` and NumPy will add 5 to each element of `foo`. The same goes for subtraction multiplication, division, and all other binary arithmetic operations.

``````foo + 5
## array([[9, 8],
##        [6, 5]])
``````