0
0
NumPydata~5 mins

np.linspace() for evenly spaced arrays in NumPy

Choose your learning style9 modes available
Introduction

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.

When you want to create a smooth range of numbers between a start and end value.
When plotting graphs and you need points evenly spaced on the x-axis.
When you want to divide a distance or time into equal parts for analysis.
When you need a fixed number of samples between two values for simulations.
When you want to generate test data with equal intervals.
Syntax
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.

Examples
This creates 5 numbers evenly spaced from 0 to 10, including 10.
NumPy
import numpy as np

# Example 1: Basic usage
array = np.linspace(0, 10, 5)
print(array)
This creates 5 numbers evenly spaced from 0 up to but not including 10.
NumPy
import numpy as np

# Example 2: Without including the endpoint
array = np.linspace(0, 10, 5, endpoint=False)
print(array)
When num=1, the output is just the start value.
NumPy
import numpy as np

# Example 3: Only one number requested
array = np.linspace(5, 15, 1)
print(array)
All numbers are the same because start and stop are equal.
NumPy
import numpy as np

# Example 4: Start and stop are the same
array = np.linspace(7, 7, 3)
print(array)
Sample Program

This program shows how np.linspace() creates arrays with and without including the stop value.

NumPy
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)
OutputSuccess
Important Notes

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.

Summary

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.