Mastering arange: Effortlessly Generate Arrays in Python
NumPy arange(): How to Use np.arange()
NumPy is the fundamental Python library for numerical computing. Its most important type is an array type called ndarray
. NumPy offers a lot of array creation routines for different circumstances. arange()
is one such function based on numerical ranges. It’s often referred to as np.arange()
because np
is a widely used abbreviation for NumPy.
Creating NumPy arrays is important when you’re working with other Python libraries that rely on them, like SciPy, Pandas, Matplotlib, scikit-learn, and more. NumPy is suitable for creating and working with arrays because it offers useful routines, enables performance boosts, and allows you to write concise code.
By the end of this article, you’ll know:
- What
np.arange()
is - How to use
np.arange()
- How
np.arange()
compares to the Python built-in classrange
- Which routines are similar to
np.arange()
Let’s see np.arange()
in action!
Return Value and Parameters of np.arange()
NumPy arange()
is one of the array creation routines based on numerical ranges. It creates an instance of ndarray
with evenly spaced values and returns the reference to it.
You can define the interval of the values contained in an array, space between them, and their type with four parameters of arange()
:
The first three parameters determine the range of the values, while the fourth specifies the type of the elements:
start
is the number (integer or decimal) that defines the first value in the array.stop
is the number that defines the end of the array and isn’t included in the array.step
is the number that defines the spacing (difference) between each two consecutive values in the array and defaults to1
.dtype
is the type of the elements of the output array and defaults toNone
.
step
can’t be zero. Otherwise, you’ll get a ZeroDivisionError
. You can’t move away anywhere from start
if the increment or decrement is 0
.
If dtype
is omitted, arange()
will automatically determine the appropriate data type based on the input values.
Range Arguments of np.arange()
Now that you know the basic parameters of np.arange()
, let’s explore different scenarios of using it.
Providing All Range Arguments
In the most common usage, you provide all range arguments to np.arange()
. This includes start
, stop
, step
, and dtype
.
In Example 1, an array with integers from 0 to 10 (exclusive) is created with a step of 2. The data type is explicitly set to integer.
In Example 2, an array with floating-point numbers from 3.5 to 10.5 (exclusive) is created with a step of 0.5. The data type is explicitly set to float.
Providing Two Range Arguments
You can also provide only two range arguments: start
and stop
. In this case, step
defaults to 1.
In the above example, an array with integers from 5 to 15 (exclusive) is created with a default step of 1.
Providing One Range Argument
If you provide only one range argument, it is considered as the stop
value. start
defaults to 0, and step
defaults to 1.
In the above example, an array with integers from 0 to 10 (exclusive) is created with a default start value of 0 and a default step of 1.
Providing Negative Arguments
np.arange()
also supports negative arguments for both the start and step values.
In the above example, an array with integers from 10 to -5 (exclusive) is created with a step of -1.
Counting Backwards
You can utilize np.arange()
to count backward by providing the stop
value as the first argument and the start
value as the second argument. This will create an array with values in reverse order.
In the above example, an array with integers from 10 to 0 (exclusive) is created with a step of -1.
Getting Empty Arrays
If the step value is such that no values are within the given range, an empty array will be returned.
In the above example, the step value of 1 doesn’t satisfy the condition to generate any values within the given range, so an empty array is returned.
Data Types of np.arange()
By default, the data type of the elements in the output array is determined automatically based on the input values. However, you can also explicitly set the data type using the dtype
parameter.
In the above examples, the first array has integers as input values, so the data type is automatically set to int64
. The second array has floating-point numbers as input values, so the data type is explicitly set to float64
.
Beyond Simple Ranges With np.arange()
The np.arange()
function is not limited to simple numerical ranges. It can also create arrays with more complex patterns.
In Example 1, an array with a non-integer step value is created. This allows for generating an array with decimal values.
In Example 2, np.arange()
is used to generate a range of dates by providing datetime
objects as input values. The step value is set as a timedelta object representing one day.
Comparison of range
and np.arange()
In Python, the built-in range()
function is commonly used for generating sequences of numbers. How does np.arange()
compare to range()
?
Parameters and Outputs
range()
accepts three integer arguments: start
, stop
, and step
. The start
argument defaults to 0, and the step
argument defaults to 1 if not provided.
In contrast, np.arange()
accepts both integer and decimal arguments for start
, stop
, and step
. Additionally, it allows for specifying the data type of the array elements using the dtype
parameter.
The outputs of range()
and np.arange()
are different as well. range()
returns a special iterator object called a range object. On the other hand, np.arange()
returns a NumPy array.
Creating Sequences
range()
is suitable for generating sequences of integers within a specified range. However, it only supports integer values and cannot handle decimal or non-integer step values.
On the other hand, np.arange()
offers more flexibility in creating sequences. It can handle floating-point numbers, decimal step values, and even non-numeric types like datetime objects.
Python for Loops
A common use case for range()
is to iterate over a sequence of numbers in a for loop:
With np.arange()
, you can achieve the same result:
However, np.arange()
provides additional functionality beyond simple iteration. It allows for creating arrays directly, enabling more efficient and concise code in many cases.
Other Routines Based on Numerical Ranges
NumPy offers several other routines and functions that are based on numerical ranges. These include:
np.linspace()
: Generates an array with a specified number of elements within a given range, including the start and end values.np.logspace()
: Generates an array with a specified number of logarithmically spaced elements within a given range.np.geomspace()
: Generates an array with a specified number of geometrically spaced elements within a given range.
Each of these routines has its own specific use cases and benefits, so it’s worth exploring them further depending on your needs.
Quick Summary
In this article, you learned how to use np.arange()
to create arrays based on numerical ranges in NumPy. You explored different scenarios of providing range arguments, setting data types, and handling complex patterns. Additionally, you compared np.arange()
to the built-in range()
function and discovered other routines based on numerical ranges in NumPy.
NumPy’s np.arange()
is a powerful tool for creating and manipulating arrays efficiently in Python. It offers flexibility, performance boosts, and concise code, making it a valuable asset for numerical computing and data analysis tasks.
Conclusion
NumPy’s np.arange()
function provides a convenient way to create arrays based on numerical ranges in Python. By using this function, you can easily generate arrays of integers or floating-point numbers with specified intervals. Understanding how to use np.arange()
opens up opportunities for working with arrays in NumPy and using them in conjunction with other Python libraries.