We use np.linspace() to create numbers that are evenly spaced between two points. This helps when we want smooth steps or ranges in data.
np.linspace() for evenly spaced arrays in NumPy
import numpy as np # Create an array of evenly spaced numbers np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
start is where the sequence begins.
stop is where the sequence ends.
num is how many numbers you want (default is 50).
endpoint=True means the stop value is included.
import numpy as np # Example 1: Basic usage array = np.linspace(0, 10, 5) print(array)
import numpy as np # Example 2: Without including the endpoint array = np.linspace(0, 10, 5, endpoint=False) print(array)
num=1, the output is just the start value.import numpy as np # Example 3: Only one number requested array = np.linspace(5, 15, 1) print(array)
import numpy as np # Example 4: Start and stop are the same array = np.linspace(7, 7, 3) print(array)
This program shows how np.linspace() creates arrays with and without including the stop value.
import numpy as np # Create an array from 0 to 20 with 6 evenly spaced numbers array_before = np.linspace(0, 20, 6) print("Array before changing endpoint:", array_before) # Create an array from 0 to 20 with 6 numbers, excluding the endpoint array_after = np.linspace(0, 20, 6, endpoint=False) print("Array after excluding endpoint:", array_after)
Time complexity is O(num) because it creates an array of size num.
Space complexity is also O(num) for storing the array.
Common mistake: forgetting that endpoint=True includes the stop value, which changes spacing.
Use np.linspace() when you want a fixed number of points evenly spaced. Use np.arange() when you want points spaced by a fixed step size.
np.linspace() creates evenly spaced numbers between start and stop.
You can control how many numbers and whether to include the stop value.
It is useful for smooth ranges in data and plotting.