NumPy: arange() and linspace() to generate evenly spaced values

Modified: | Tags: Python, NumPy

In NumPy, the np.arange() and np.linspace() functions generate an array (ndarray) of evenly spaced values. You can specify the interval in np.arange() and the number of values in np.linspace().

The NumPy version used in this article is as follows. Note that functionality may vary between versions.

import numpy as np

print(np.__version__)
# 1.26.1

How to use np.arange()

np.arange() is similar to Python's built-in range() function. See the following article for range().

Like range(), np.arange() generates an ndarray with evenly spaced values according to the specified arguments:

  • np.arange(stop)
    • 0 <= n < stop with an interval of 1
  • np.arange(start, stop)
    • start <= n < stop with an interval of 1
  • np.arange(start, stop, step)
    • start <= n < stop with an interval of step
print(np.arange(3))
# [0 1 2]

print(np.arange(3, 10))
# [3 4 5 6 7 8 9]

print(np.arange(3, 10, 2))
# [3 5 7 9]

Unlike range(), floating-point numbers (float) can be specified as arguments in np.arange().

print(np.arange(0.3, 1.0, 0.2))
# [0.3 0.5 0.7 0.9]

Like range(), np.arange() accepts negative values. Additionally, it produces an empty ndarray when there are no matching values.

print(np.arange(-3, 3))
# [-3 -2 -1  0  1  2]

print(np.arange(10, 3))
# []

print(np.arange(10, 3, -2))
# [10  8  6  4]

While data type (dtype) is automatically selected, it can be manually specified via the dtype argument.

a = np.arange(3, 10)
print(a)
# [3 4 5 6 7 8 9]

print(a.dtype)
# int64

a_float = np.arange(3, 10, dtype=float)
print(a_float)
# [3. 4. 5. 6. 7. 8. 9.]

print(a_float.dtype)
# float64

For details on data types in NumPy, refer to the following article.

How to use np.linspace()

Basic usage

With np.linspace(), you can specify the number of elements instead of the interval.

Specify the starting value in the first argument start, the end value in the second stop, and the number of elements in the third num. The interval is automatically calculated based on these values.

print(np.linspace(0, 10, 3))
# [ 0.  5. 10.]

print(np.linspace(0, 10, 4))
# [ 0.          3.33333333  6.66666667 10.        ]

print(np.linspace(0, 10, 5))
# [ 0.   2.5  5.   7.5 10. ]

It also handles the case where start > stop appropriately.

print(np.linspace(10, 0, 5))
# [10.   7.5  5.   2.5  0. ]

The data type (dtype) of the generated array can be specified with the dtype argument. Note that by default, even if an array of integers is generated, it becomes floating-point numbers (float).

a = np.linspace(0, 10, 3)
print(a)
# [ 0.  5. 10.]

print(a.dtype)
# float64

a_int = np.linspace(0, 10, 3, dtype=int)
print(a_int)
# [ 0  5 10]

print(a_int.dtype)
# int64

Specify whether to include stop: endpoint

By default, stop is included in the result; setting endpoint to False excludes it.

print(np.linspace(0, 10, 5))
# [ 0.   2.5  5.   7.5 10. ]

print(np.linspace(0, 10, 5, endpoint=False))
# [0. 2. 4. 6. 8.]

The relationship between the endpoint argument and the interval (step) is as follows:

  • endpoint=True (default)
    • step = (stop - start) / (num - 1)
  • endpoint=False
    • step = (stop - start) / num

Get the interval: retstep

Setting the retstep argument to True returns a tuple (resulting_ndarray, step), where step is the interval.

result = np.linspace(0, 10, 5, retstep=True)
print(result)
# (array([ 0. ,  2.5,  5. ,  7.5, 10. ]), 2.5)

print(type(result))
# <class 'tuple'>

print(result[0])
# [ 0.   2.5  5.   7.5 10. ]

print(result[1])
# 2.5

If you only want to check step, you can get the second element by indexing.

print(np.linspace(0, 10, 5, retstep=True)[1])
# 2.5

print(np.linspace(0, 10, 5, retstep=True, endpoint=False)[1])
# 2.0

Convert to reverse order

Generating a reverse order array with np.arange() requires appropriate arguments, which can be cumbersome.

print(np.arange(3, 10, 2))
# [3 5 7 9]

print(np.arange(9, 2, -2))
# [9 7 5 3]

Using the slice [::-1] or np.flip() allows for easy reversal of the result.

print(np.arange(3, 10, 2)[::-1])
# [9 7 5 3]

print(np.flip(np.arange(3, 10, 2)))
# [9 7 5 3]

In the case of np.linspace(), simply swapping the first argument (start) with the second (stop) can easily reverse the order if endpoint=True. The same result can be achieved using the slice [::-1] or np.flip().

print(np.linspace(0, 10, 5))
# [ 0.   2.5  5.   7.5 10. ]

print(np.linspace(10, 0, 5))
# [10.   7.5  5.   2.5  0. ]

print(np.linspace(0, 10, 5)[::-1])
# [10.   7.5  5.   2.5  0. ]

print(np.flip(np.linspace(0, 10, 5)))
# [10.   7.5  5.   2.5  0. ]

If endpoint=False, swapping the first argument (start) with the second (stop) does not reverse the order. Using the slice [::-1] or np.flip() makes it easy.

print(np.linspace(0, 10, 5, endpoint=False))
# [0. 2. 4. 6. 8.]

print(np.linspace(10, 0, 5, endpoint=False))
# [10.  8.  6.  4.  2.]

print(np.linspace(0, 10, 5, endpoint=False)[::-1])
# [8. 6. 4. 2. 0.]

print(np.flip(np.linspace(0, 10, 5, endpoint=False)))
# [8. 6. 4. 2. 0.]

Convert to multi-dimensional arrays

To create multi-dimensional arrays, use the reshape() method, since neither np.arange() nor np.linspace() have an argument to specify the shape.

print(np.arange(12).reshape(3, 4))
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]

print(np.arange(24).reshape(2, 3, 4))
# [[[ 0  1  2  3]
#   [ 4  5  6  7]
#   [ 8  9 10 11]]
# 
#  [[12 13 14 15]
#   [16 17 18 19]
#   [20 21 22 23]]]
print(np.linspace(0, 10, 12).reshape(3, 4))
# [[ 0.          0.90909091  1.81818182  2.72727273]
#  [ 3.63636364  4.54545455  5.45454545  6.36363636]
#  [ 7.27272727  8.18181818  9.09090909 10.        ]]

print(np.linspace(0, 10, 24).reshape(2, 3, 4))
# [[[ 0.          0.43478261  0.86956522  1.30434783]
#   [ 1.73913043  2.17391304  2.60869565  3.04347826]
#   [ 3.47826087  3.91304348  4.34782609  4.7826087 ]]
# 
#  [[ 5.2173913   5.65217391  6.08695652  6.52173913]
#   [ 6.95652174  7.39130435  7.82608696  8.26086957]
#   [ 8.69565217  9.13043478  9.56521739 10.        ]]]

Related Categories

Related Articles