Problem: How to create a sequence of linearly increasing values?
Solution: Use NumPy’s
np.arange([start,] stop[, step]) function creates a new NumPy array with evenly-spaced integers between
start (inclusive) and
stop (exclusive). The
step size defines the difference between subsequent values. For example,
np.arange(1, 6, 2) creates the NumPy array
[1, 3, 5].
import numpy as np # np.arange(stop) >>> np.arange(10) array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) # np.arange(start, stop) >>> np.arange(2, 10) array([2, 3, 4, 5, 6, 7, 8, 9]) # np.arange(start, stop, step) >>> np.arange(2, 10, 2) array([2, 4, 6, 8]) # np.arange(start, stop, step, dtype) >>> np.arange(2, 10, 2, float) array([2., 4., 6., 8.])
Related Video NumPy Arange
NumPy Data Science Puzzle
Can you solve the following puzzle regarding the NumPy arange function:
import numpy as np # save $122.50 per month x = 122.5 net_wealth = np.arange(0, 1000, x) # how long to save > $1000? print(len(net_wealth))
What is the output of this puzzle?
Numpy is a popular Python library for data science focusing on linear algebra.
This puzzle is about the numpy arange function. The arange function is everywhere in data science.
You might know the Python built-in
range(x,y,z) function that creates a sequence of linear progressing values. The sequence starts from x, increases the values linearly by y, and ends if the value becomes larger than z.
arange(x,y,z) function is similar but creates a numpy array and works with float numbers as well.
Note that a common mistake in this puzzle is to not account for the first value of the array: 0.
Are you a master coder?
Test your skills now!
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.