When it comes to creating a sequence of values, linspace and arange are two commonly used NumPy functions.
Here is the subtle difference between the two functions:
- linspace allows you to specify the number of steps
- arange allows you to specify the size of the steps
The following examples show how to use each function in practice.
Example 1: How to Use np.linspace
The np.linspace() function uses the following basic syntax:
np.linspace(start, stop, num, …)
where:
- start: The starting value of the sequence
- stop: The end value of the sequence
- num: the number of values to generate
The following code shows how to use np.linspace() to create 11 values evenly spaced between 0 and 20:
import numpy as np
#create sequence of 11 evenly spaced values between 0 and 20
np.linspace(0, 20, 11)
array([ 0., 2., 4., 6., 8., 10., 12., 14., 16., 18., 20.])
The result is an array of 11 values that are evenly spaced between 0 and 20.
Using this method, np.linspace() automatically determines how far apart to space the values.
Example 2: How to Use np.arange
The np.arange() function uses the following basic syntax:
np.arange(start, stop, step, …)
where:
- start: The starting value of the sequence
- stop: The end value of the sequence
- step: The spacing between values
The following code shows how to use np.arange() to create a sequence of values between 0 and 20 where the spacing between each value is 2:
import numpy as np
#create sequence of values between 0 and 20 where spacing is 2
np.arange(0, 20, 2)
array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
The result is a sequence of values between 0 and 20 where the spacing between each value is 2.
Using this method, np.arange() automatically determines how many values to generate.
If we use a different step size (like 4) then np.arange() will automatically adjust the total number of values generated:
import numpy as np
#create sequence of values between 0 and 20 where spacing is 4
np.arange(0, 20, 4)
array([ 0, 4, 8, 12, 16])
Additional Resources
The following tutorials explain how to perform other common operations in Python:
How to Fill NumPy Array with Values
How to Replace Elements in NumPy Array
How to Count Unique Values in NumPy Array