Python: range(), numpy.arange(), and numpy.linspace()

Rahul S
3 min readSep 9, 2023

1. range()

  • range() is a built-in Python function used to create a sequence of integers from a starting value (inclusive) to an ending value (exclusive).
range([start], stop, [step])
#Generating a simple sequence of numbers:

for i in range(5):
print(i)
# Output: 0 1 2 3 4
#Specifying start, stop, and step values:

for i in range(1, 10, 2):
print(i)
# Output: 1 3 5 7 9
# Creating a list from a range:

my_list = list(range(3, 15, 3))
# my_list will be [3, 6, 9, 12]

2. numpy.arange()

  • numpy.arange() is a function from the NumPy library used to create arrays with evenly spaced values within a specified range.
  • It allows specifying the start, stop, and step values.
numpy.arange([start], stop, [step], dtype=None)
#Creating an array with arange:

import numpy as np
arr = np.arange(0, 10, 2)
# arr will be array([0, 2, 4, 6, 8])
#Specifying a float data type:

import numpy as np
arr = np.arange(0, 1, 0.1, dtype=float)

# arr will be array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
# Using arange for creating a sequence of dates:

import numpy as np
start_date = np.datetime64('2023-01-01')
end_date = np.datetime64('2023-01-10')

date_range = np.arange(start_date, end_date, np.timedelta64(1, 'D'))

# date_range will be array(['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04',
# '2023-01-05', '2023-01-06', '2023-01-07', '2023-01-08',
# '2023-01-09'], dtype='datetime64[D]')

3. numpy.linspace()

  • numpy.linspace() is a function from the NumPy library used to create evenly spaced values over a specified range.
  • It generates a specified number of values between a start and stop point, inclusive by default.
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
#Creating an array with linspace:

import numpy as np
arr = np.linspace(0, 1, 5)

# arr will be array([0. , 0.25, 0.5 , 0.75, 1. ])

--

--