How to Create a Sequence of Evenly Spaced Values [Vanilla Python & Numpy Linspace]

Rate this post

Problem: How to create a sequence of evenly-spaced values

Example: Given three arguments: start=10, stop=20, number_of_values=11. How do you create a sequence of 11 values x0, x1, …, x10 where two subsequent values xi and x(i-1) have the same distance for all i in {0, …, 10}.

# Given
start = 10
stop = 20
num_vals = 11

# Desired
magic_method(start, stop, num_vals)
# Returns [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

Next, you’ll learn two methods that accomplish this goal!

Method 1: Vanilla Python

You can create a sequence of a certain number of evenly spaced floats in two steps:

  • Calculate the difference between two subsequent numbers as (stop-start)/(num_vals-1) assuming you want to include endpoints.
  • Create a list of evenly spaced numbers using list comprehension: [start + i * delta for i in range(num_vals)]
# Problem Formulation
start = 10
stop = 20
num_vals = 11

# Method 1: Vanilla Python
delta = (stop-start)/(num_vals-1)
evenly_spaced = [start + i * delta for i in range(num_vals)]

Method 2: NumPy linspace()

How does it work? Have a look at this graphic that explains NumPy’s linspace function visually:

NumPy np.linspace()

It takes only three arguments in most cases: start, stop, and num. To accomplish the goal, you’d use the following code:

# Problem Formulation
start = 10
stop = 20
num_vals = 11

# Method 2: NumPy Linspace
import numpy as np
print(np.linspace(start, stop, num_vals))
# [10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20.]

Note that the result is a list of floats. To convert them to an int, you can use the following one-liner instead:

print([int(x) for x in np.linspace(start, stop, num_vals)])
# [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

NumPy linspace() Puzzle

Can you solve this Python puzzle?

import numpy as np

year = np.linspace(0, 365, 366)
print(int(year[-1] – year[-2]))

Exercise: What is the output of this puzzle?

You can also solve it on our interactive Python puzzle app and track your Python skills here:

linspace() NumPy Puzzle

Numpy is a popular Python library for data science focusing on linear algebra.

This puzzle is about the useful function linspace. In particular, linspace(start, stop, num) returns evenly spaced numbers over a given interval [start, stop], with stop included.

For example, linspace(0,3,4) returns the numpy array sequence 0,1,2,3 (i.e., 4 evenly spaced numbers).

This function is particularly useful when plotting (or evaluating) a function. The result of the function applied to evenly spaced numbers reveals how it progresses for growing parameter values.

Related Video

How to Use np.linspace() in Python? A Helpful Illustrated Guide