Skip to main content

13.1) Operations


Arithmetic operations on NumPy arrays are done element by element (like in Fortan). No need to write a loop to add each element one by one as we did with lists, you just add the two arrays together:

>>> a=np.array([1,2,3,4])
>>> b=np.array([10,20,30,40])
>>> a + b
array([11, 22, 33, 44])
>>> b - a
array([ 9, 18, 27, 36])

Arrays can also be multiplied of divided by each other.

You can also mix arrays with scalars in operations:

>>> a * 2   # all array elements are multiplied by two
array([ 2,  4,  6, 8])
>>> a**2  # all array elements are squared
array([ 1,  4,  9, 16])

This is different to the behaviour of lists. Remember, multiplying a list by two has the effect of repeating the list twice. Here multiplying an array by two has the effect of multiplying all its elements by two.