Skip to content

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 class range
  • 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():

numpy.arange([start, ]stop, [step, ], dtype=None) -> numpy.ndarray

The first three parameters determine the range of the values, while the fourth specifies the type of the elements:

  1. start is the number (integer or decimal) that defines the first value in the array.
  2. stop is the number that defines the end of the array and isn’t included in the array.
  3. step is the number that defines the spacing (difference) between each two consecutive values in the array and defaults to 1.
  4. dtype is the type of the elements of the output array and defaults to None.

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.

import numpy as np
# Example 1
arr = np.arange(0, 10, 2, dtype=int)
print(arr) # Output: [0 2 4 6 8]
# Example 2
arr = np.arange(3.5, 10.5, 0.5, dtype=float)
print(arr) # Output: [3.5 4. 4.5 5. 5.5 6. 6.5 7. 7.5 8. 8.5 9. 9.5 10. ]

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.

import numpy as np
arr = np.arange(5, 15)
print(arr) # Output: [ 5 6 7 8 9 10 11 12 13 14]

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.

import numpy as np
arr = np.arange(10)
print(arr) # Output: [0 1 2 3 4 5 6 7 8 9]

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.

import numpy as np
arr = np.arange(10, -5, -1)
print(arr) # Output: [10 9 8 7 6 5 4 3 2 1 0 -1 -2 -3 -4]

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.

import numpy as np
arr = np.arange(10, 0, -1)
print(arr) # Output: [10 9 8 7 6 5 4 3 2 1]

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.

import numpy as np
arr = np.arange(10, 0, 1)
print(arr) # Output: []

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.

import numpy as np
# Automatic data type determination
arr = np.arange(0, 10)
print(arr.dtype) # Output: int64
# Explicitly setting data type
arr = np.arange(0, 10, dtype=float)
print(arr.dtype) # Output: float64

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.

import numpy as np
# Example 1: Creating an array with a non-integer step value
arr = np.arange(0, 1, 0.1)
print(arr) # Output: [0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
# Example 2: Using `np.arange()` to generate timestamps
import datetime
start_date = datetime.datetime(2021, 1, 1)
end_date = datetime.datetime(2021, 1, 10)
step = datetime.timedelta(days=1)
date_range = np.arange(start_date, end_date, step)
print(date_range) # Output: [datetime.datetime(2021, 1, 1, 0, 0) datetime.datetime(2021, 1, 2, 0, 0)
# datetime.datetime(2021, 1, 3, 0, 0) datetime.datetime(2021, 1, 4, 0, 0) datetime.datetime(2021, 1, 5, 0, 0)
# datetime.datetime(2021, 1, 6, 0, 0) datetime.datetime(2021, 1, 7, 0, 0) datetime.datetime(2021, 1, 8, 0, 0)
# datetime.datetime(2021, 1, 9, 0, 0)]

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:

for i in range(5):
print(i)

With np.arange(), you can achieve the same result:

import numpy as np
for i in np.arange(5):
print(i)

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.