np.arange(stop) generates values from 0 up to, but not including, stop; np.arange(start, stop, step) generalizes this with an explicit start and step size, which, unlike range(), can be a float, letting you generate fractional sequences. Because of floating-point rounding error, the exact number of elements produced by a float step can sometimes be off by one from what you'd expect mathematically, which is one reason np.linspace() is often preferred when you need a precise, known number of points.
1Understanding np.arange()
np.arange(stop) generates values from 0 up to, but not including, stop; np.arange(start, stop, step) generalizes this with an explicit start and step size, which, unlike range(), can be a float, letting you generate fractional sequences. Because of floating-point rounding error, the exact number of elements produced by a float step can sometimes be off by one from what you'd expect mathematically, which is one reason np.linspace() is often preferred when you need a precise, known number of points.
For float ranges where you need an exact, known number of points rather than a step size, use np.linspace(start, stop, num) instead of np.arange() — floating-point rounding can make arange's element count slightly unpredictable.
import numpy as np
arr = np.arange(0, 10, 2)
print(arr)2Practical Example
Here is a real-world application of np.arange() showing how it is used in production NumPy code.
import numpy as np
arr = np.arange(0, 1, 0.25)
print(arr)3Best Practices
Follow these guidelines when working with np.arange():
1. Use np.arange() for integer sequences or when you specifically know the step size you want
2. Use np.linspace() instead of np.arange() when you need an exact number of evenly spaced float values, to avoid floating-point step-count surprises
3. Specify an explicit dtype when the default type inference isn't what you want
Tip: For float ranges where you need an exact, known number of points rather than a step size, use np.linspace(start, stop, num) instead of np.arange() — floating-point rounding can make arange's element count slightly unpredictable.
import numpy as np
arr = np.arange(0, 10, 2)
print(arr)