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

Chapter 3: Array operations

Numerical ranges

face Josiah Wang Joe Stacey

Let’s say we need to multiply each number from 0 to 9 by 2, and then subtract 3 from each number. Here is how you would do it in pure Python, with the range() object and list comprehension.

>>> numbers = [i*2-3 for i in range(10)]
>>> print(numbers)
[-3, -1, 1, 3, 5, 7, 9, 11, 13, 15]

Using NumPy, you can avoid the for-loop altogether! Just use its version of the np.arange() function, which returns a np.array. Then perform the multiplication and subtraction directly on the np.array.

>>> x = np.arange(10)
>>> numbers = x*2 - 3
>>> print(numbers)
[-3 -1  1  3  5  7  9 11 13 15]

This process of applying operations to whole arrays instead of individual elements is called vectorisation (or a vectorised operation). No loops required! Vectorisation allows you to perform such element-wise operations more efficiently and more compactly.

Otherwise, the function np.arange() acts just like Python’s range() (complete with the start and step arguments).

If you would like to generate a range of numbers that are not integers, then you should use np.linspace() instead. It generates a np.array with values spaced linearly in a specified interval. Like any np.array, you can also perform vectorised operations on the resulting np.array.

>>> x = np.linspace(0, 10, num=5) 
>>> print(x)
[ 0.   2.5  5.   7.5 10. ]
>>> y = x**2
>>> print(y)
[  0.     6.25  25.    56.25 100.  ]

There are a few more functions like np.logspace() that might be useful to you at some point. Again, always refer to the official documentation for more details!