The NumPy function
np.arange([start,] stop[, step]) creates a new NumPy array with evenly spaced numbers between
start (inclusive) and
stop (exclusive) with the given step size. For example,
np.arange(1, 6, 2) creates the NumPy array
[1, 3, 5].
Here are the four most recent usages of the NumPy arange function:
import numpy as np # np.arange(stop) >>> np.arange(10) [0 1 2 3 4 5 6 7 8 9] # np.arange(start, stop) >>> np.arange(2, 10) [2 3 4 5 6 7 8 9] # np.arange(start, stop, step) >>> np.arange(2, 10, 2) [2 4 6 8] # np.arange(start, stop, step, dtype) >>> np.arange(2, 10, 2, float) [2. 4. 6. 8.]
Here’s a visual representation of the previous code examples:
Still struggling with understanding NumPy’s
arange() function? Read on, start with level 1 and pass all 6 levels!
[Reading time: 3-7 minutes] – Or watch the video.
Level 1: numpy.arange
The NumPy arange function (no it’s not NumPy arrange) creates a NumPy array with evenly spaced numbers within a fixed interval.
In this article, I lead you step-by-step through all the different use cases of the NumPy arange function. The article ends with a short FAQ – Feel free to add your own question as a comment!
Level 2: numpy.arange(stop)
Let’s start with an example of the basic usage of NumPy arange where you only specify the stop argument.
Say, you want to get seven subsequent numbers for seven weekdays (0: Monday, 1: Tuesday, 2: Wednesday, 3: Thursday, 4: Friday, 5: Saturday, 6: Sunday). Your NumPy array starts with index 0 and ends in index 6.
Similar to many other sequence operations,
np.arange() implicitly starts with index 0. If you only specify one single argument, you implicitly set the start argument to 0.
Here is an example of the NumPy arange function with a single argument:
np.arange(7) # np.array([0, 1, 2, 3, 4, 5, 6])
The result is a NumPy array with ten elements starting from the implicitly chosen index 0 (inclusive) and ending in the explicitly chosen index 7 (exclusive).
But what if we want to define a start index? Say, you want to take off Mondays, i.e., skip the start index 0, because you hate being anxious on Sunday evenings (get yourself a new job, man!) …
Level 3: numpy.arange(start, stop)
… Nothing simpler than that. If you add a second argument, the Python interpreter interprets (*lol*) the first one as the start index and the second one as the end index.
Here is an example of the NumPy arange function with two arguments:
np.arange(1, 7) # np.array([1, 2, 3, 4, 5, 6])
Ok, we mastered the two-argument version as well. Let’s move on to the next level.
Level 4: np.arange(start, stop, step)
As a next step, you decide that you want to start your week on Tuesdays, as previously. But as work is so exhausting, you take every other day off as well (luckily, you do have a solid salary as a programmer, don’t you?). It’s getting interesting: add a third argument–that is the step size 2. Here is an example:
np.arange(1, 7, 2) # np.array([1, 3, 5])
Well done, you only work on Tuesdays, Thursdays, and Saturdays now! All programmers are lazy, you are lazy, so you are a programmer (find the bug).
Level 5: np.arange(start, stop, step, dtype)
As you put your working days [1, 3, 5] into your company’s tracking system, it complains about the wrong formatting of your input numpy array. It expects all NumPy array values to be formatted as a float rather than an integer value. “What a design flaw for weekday data!”.
But it’s a simple fix using the fourth argument of the
arange() function: the data type of the output array, i.e., dtype. As
dtype argument, you can use two kinds of data types. First, use traditional language-specific data types such as float and integer. Second, use NumPy-specific data types such as
For instance, the NumPy-specific data types
np.float32 allow for an integer value with 16 bits (=2 bytes) or a float value with 32 bits (=4 bytes). Keep in mind that more bits lead to higher overhead but more powerful ranges of numbers (or precision in the case of float data types).
Here is a collection of dtypes you can use (check out this excellent post if you need more information about NumPy dtypes):
bool: The default boolean data type in Python (1 Byte).
int: The default Python integer data type in Python (4 or 8 Bytes).
float: The default float data type in Python (8 Bytes).
complex: The default complex data type in Python (16 Bytes).
np.int8: Integer (1 Byte).
np.int16: Integer (2 Bytes).
np.int32: Integer (4 Bytes).
np.int64: Integer (8 Bytes).
np.float16: Float (2 Bytes).
np.float32: Float (4 Bytes).
np.float64: Float (8 Bytes).
Here is an example for the 4-argument version of
np.arange(1, 7, 2, dtype=np.float32) # np.array([1., 3., 5.])
Level 6: Examples
Now, you have mastered all the four different uses of the NumPy arange function. To wrap things up, make sure to skim over this more comprehensive list of examples:
print(np.arange(10)) # np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) print(np.arange(2, 10, 3)) # np.array([2, 5, 8]) print(np.arange(1.5, 10., 1.5)) # np.array([1.5, 3., 4.5, 6., 7.5, 9. ]) print(np.arange(10, 1, -2)) # np.array([10, 8, 6, 4, 2]) print(np.arange(9.7, 9.2, -0.1)) # np.array([9.7, 9.6, 9.5, 9.4, 9.3]) print(np.arange(1, 1, 1)) # np.array() print(np.arange(1, 5, dtype=np.int16)) # np.array([1, 2, 3, 4]) print(np.arange(1, 5, dtype=np.float32)) # np.array([1., 2., 3., 4.])
Are you a master coder?
Test your skills now!
Diving Deep into NumPy Arange
Congratulations, you now know the most important details about the NumPy arange function. But you still may have a few questions. Let’s answer them one by one!
When should I use np.arange() and when np.linspace()?
Use np.arange() if you want to create integer sequences with evenly distributed integer values within a fixed interval.
Use np.linspace() if you have a non-integer step size. The NumPy linspace function handles the endpoints better. This prevents you from introducing unnecessary bugs into your code. One such bug is for example that you assume an endpoint is not in the NumPy array while it is because of the floating-point arithmetic.
What are some use cases of np.arange()?
NumPy is mostly about multi-dimensional matrices. It is common to create a 1D NumPy array with the NumPy arange function and to transform it immediately into a 2D array using the np.reshape() function. An example is the following where we create a 2D array with three rows and two columns from a 1D array.
np.arange(6).reshape((3, 2)) # array([[0, 1], # [2, 3], # [4, 5]])
Short Summary of NumPy Arange()
First, you need to import the NumPy library:
import numpy as np
Now, you can use the NumPy arange function to create sequences with equal step sizes in various ways. Go over the table and study the examples thoroughly:
|Example||Resulting NumPy Array|
Where to go from here?
How to join the top earners in any field? Read more books!
Because I always find it difficult to find time to learn, I have written a new NumPy book that can be entirely consumed in small doses — for example as you drink your daily morning coffee.
Don’t miss out on this exciting new way of learning to code — it’s so much more fun! 🙂