Let’s learn How to generate evenly spaced sample in Numpy Python library. We will use Numpy linspace method for that purpose.
To generate evenly spaced sample within given interval you may need linpsace function. It generates the array and takes starting point, end point and the number of needed elements.
More on Numpy linspace method
The `linspace` method in Numpy can be used to generate evenly spaced sample within given interval. It takes starting point, end point and the number of needed elements as its parameters.
The syntax for the `linspace` method is as follows:
linspace(start, end, num=5)
Where:
start is the starting point of the interval end is the end point of the interval num is the number of elements to be generated
The simpliest example
Let’s see how to generate even sample from 0 to 100. I will need 5 elements in my sample array.
import numpy as np cities = ["New York", "London", "Austin", "Chicago", "Quebec"] my_linspace_array = np.linspace(0, 100, len(cities)) print(f"This is my sample array generated using linspace method: " f"\n {my_linspace_array}")
More advanced example
You can even add more parameters to your code:
import numpy as np my_array = ([0, 20, 25, 40, 100]) my_linspace_array = np.linspace(min(my_array), max(my_array), len(my_array)) print(f"This is my sample array generated using linspace method: " f"\n {my_linspace_array}")
The result is the same. Linspace interval is fully parametrized by my_array list.
Other parameters of Numpy linspace method
The `linspace` method in Numpy has several other parameters that can be used to customize the output.

* `endpoint` : If set to True, the end point will be included in the output array. The default value is True.
* `dtype` : The data type of the output array. The default value is float.
* `retstep` : If set to True, the step size between elements in the output array will be returned as well. The default value is False.
For example, the following code will generate 10 evenly spaced sample from 0 to 100, but the end point will not be included in the output array:
import numpy as np my_linspace_array = np.linspace(0, 100, 10, endpoint=False) print(f"This is my sample array generated using linspace method: " f"\n {my_linspace_array}")