Labs ICT
Pro Login

arange & linspace

Generating sequences of numbers the easy way.

arange & linspace

Creating arrays with sequences is super common in NumPy. Think of it like creating number lines for your calculations. These functions are more powerful than you might think.

np.arange - The Step Function

np.arange() works like Python's range() but for floating-point numbers. You specify start, stop, and step.


import numpy as np

arr1 = np.arange(10)
arr2 = np.arange(0, 10, 2)
arr3 = np.arange(0, 1, 0.1)

print(f"0 to 9: {arr1}")
print(f"Even numbers: {arr2}")
print(f"0 to 0.9: {arr3}")
    

Here is the thing - the stop value is exclusive. So np.arange(0, 10) gives you 0 to 9, not 0 to 10.

np.linspace - The Count Function

np.linspace() creates evenly spaced numbers over a specified interval. You specify start, stop, and number of points.


import numpy as np

arr1 = np.linspace(0, 10, 5)
arr2 = np.linspace(0, 1, 11)

print(f"5 points from 0 to 10: {arr1}")
print(f"11 points from 0 to 1: {arr2}")
    

The difference from arange is that linspace includes the stop value and you specify how many points you want, not the step size.

When to Use Each

Use arange when you know the step size (like every 0.1). Use linspace when you know how many points you need (like 100 evenly spaced points).


import numpy as np

x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)

print(f"Created {len(x)} points")
print(f"First 5 x values: {x[:5]}")
print(f"First 5 y values: {y[:5]}")
    

One thing that confused me at first was when to use which. I found that for plotting, linspace is usually better because you control the density of points.

Try it Yourself →

Key Takeaways

  • np.arange() creates sequences with specified step size
  • np.linspace() creates sequences with specified number of points
  • arange excludes stop value, linspace includes it
  • Use linspace for plotting, arange for step-based sequences