create numpy array of equally spaced values from a range in python

We can use the numpy.arange() function to create an array of equally spaced values within a given range. The function takes three arguments:

  • start: the start of the range (inclusive)
  • stop: the end of the range (exclusive)
  • step: the step size between values (default is 1)

Here's an example:

main.py
import numpy as np

# create array of values from 0 to 9 with step size of 2
arr = np.arange(0, 10, 2)

print(arr)
# output: [0 2 4 6 8]
137 chars
8 lines

If we omit the step argument, it defaults to 1:

main.py
import numpy as np

# create array of values from 0 to 9 with step size of 1 (default)
arr = np.arange(0, 10)

print(arr)
# output: [0 1 2 3 4 5 6 7 8 9]
154 chars
8 lines

We can also use the numpy.linspace() function to create an array of equally spaced values with a specified number of elements. The function takes three arguments:

  • start: the start of the range (inclusive)
  • stop: the end of the range (inclusive)
  • num: the number of elements to create (default is 50)

Here's an example:

main.py
import numpy as np

# create array with 5 equally spaced values from 0 to 1 (inclusive)
arr = np.linspace(0, 1, 5)

print(arr)
# output: [0.   0.25 0.5  0.75 1.  ]
164 chars
8 lines

Note that the stop argument is inclusive in numpy.linspace(), unlike in numpy.arange().

related categories

gistlibby LogSnag