Skip to content

Effortlessly Mastering numpy arange for Python Tutorials

[

NumPy arange(): How to Use np.arange()

by Mirko Stojiljković

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 anywhere from start if the increment or decrement is 0.

If dtype is omitted, arange() will try to determine the appropriate data type based on the input values. Here are a few examples of using np.arange():

import numpy as np
# Example 1
arr1 = np.arange(5)
print(arr1)
# Output: [0 1 2 3 4]
# Example 2
arr2 = np.arange(2, 10, 2)
print(arr2)
# Output: [2 4 6 8]
# Example 3
arr3 = np.arange(1.5, 5.5, 0.5, dtype=np.float)
print(arr3)
# Output: [1.5 2. 2.5 3. 3.5 4. 4.5 5. ]

In Example 1, np.arange(5) creates an array with values from 0 to 4 (excluding 5) with a default step of 1.

In Example 2, np.arange(2, 10, 2) creates an array with values from 2 to 8 (excluding 10) with a step of 2.

In Example 3, np.arange(1.5, 5.5, 0.5, dtype=np.float) creates an array with floating-point values from 1.5 to 5.5 (excluding 6) with a step of 0.5 and a data type of float.

Range Arguments of np.arange()

Now that you know how to use np.arange(), let’s explore the range arguments you can provide to create different types of arrays.

Providing All Range Arguments

To create an array with all three range arguments (start, stop, and step), use the following syntax:

import numpy as np
arr = np.arange(start, stop, step)

Providing Two Range Arguments

If you provide only two range arguments (start and stop), np.arange() will use a default step value of 1:

import numpy as np
arr = np.arange(start, stop)

Providing One Range Argument

If you provide only one range argument (stop), np.arange() will use a default start value of 0 and a default step value of 1:

import numpy as np
arr = np.arange(stop)

Providing Negative Arguments

You can use negative values for any of the range arguments. For example:

import numpy as np
arr1 = np.arange(-5, 5)
print(arr1)
# Output: [-5 -4 -3 -2 -1 0 1 2 3 4]
arr2 = np.arange(5, -5, -1)
print(arr2)
# Output: [ 5 4 3 2 1 0 -1 -2 -3 -4]

In Example 1, np.arange(-5, 5) creates an array with values from -5 to 4 (excluding 5) with a step of 1.

In Example 2, np.arange(5, -5, -1) creates an array with values from 5 to -4 (excluding -5) with a step of -1.

Counting Backwards

You can also use np.arange() to count backward by providing appropriate range arguments. For example:

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

In this example, np.arange(10, 0, -1) creates an array with values from 10 to 1 (excluding 0) with a step of -1.

Getting Empty Arrays

If the range arguments provided to np.arange() lead to an empty array, the result will be an empty array:

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

In this example, np.arange(5, 1, -1) creates an empty array because the start value of 5 is greater than the stop value of 1.

Data Types of np.arange()

By default, if you don’t specify a data type with the dtype argument, np.arange() will try to determine the appropriate data type based on the input values. However, you can explicitly specify a data type as shown in the following example:

import numpy as np
arr = np.arange(5, dtype=np.float)
print(arr)
# Output: [0. 1. 2. 3. 4.]

In this example, np.arange(5, dtype=np.float) creates an array with floating-point values from 0 to 4.

Beyond Simple Ranges With np.arange()

np.arange() is a useful function for creating simple numerical ranges, but you can also use it in more complex scenarios. For example, you can create an array of the values of a mathematical function over a specific range using np.arange() to generate the input values. Here’s an example:

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10, 10, 0.1)
y = np.sin(x)
plt.plot(x, y)
plt.xlabel("x")
plt.ylabel("sin(x)")
plt.title("Graph of the Sine Function")
plt.show()

In this example, np.arange(-10, 10, 0.1) creates an array of input values for the sine function. The resulting array x is then used to compute the corresponding values of y using np.sin(x). Finally, the graph of the sine function is plotted using Matplotlib.

Comparison of range and np.arange()

Now that you know how to use np.arange(), let’s compare it to the Python built-in class range and see how they differ.

Parameters and Outputs

Both range and np.arange() take start, stop, and step values as parameters, but there are a few differences:

  • range only works with integers, while np.arange() can work with both integers and decimals.
  • range returns a range object, while np.arange() returns a NumPy array.
  • range is a built-in Python class, while np.arange() is a function from the NumPy library.

Creating Sequences

range is commonly used to create sequences of integers for looping, whereas np.arange() is used to create arrays with evenly spaced values. Here’s an example that demonstrates the difference:

# Using range
for i in range(5):
print(i)
# Output: 0 1 2 3 4
# Using np.arange()
import numpy as np
arr = np.arange(5)
print(arr)
# Output: [0 1 2 3 4]

In the range example, the for loop iterates over the range object and prints the integers from 0 to 4. In the np.arange() example, an array with the values from 0 to 4 is created using NumPy.

Other Routines Based on Numerical Ranges

NumPy offers other routines based on numerical ranges that are similar to np.arange(). Here are a few examples:

  • np.linspace(): Returns an array with a specified number of equally spaced values between the start and stop values.
  • np.logspace(): Returns an array with a specified number of logarithmically spaced values between the start and stop values.
  • np.geomspace(): Returns an array with a specified number of geometrically spaced values between the start and stop values.

These routines can be useful in different scenarios where you need arrays with specific spacing or distribution of values.

Quick Summary

In this tutorial, you learned how to use np.arange() in NumPy to create arrays with evenly spaced values. You can define the start, stop, and step values, as well as the data type of the elements in the output array. np.arange() is a versatile function that allows you to create a wide range of arrays based on numerical ranges.

Conclusion

NumPy’s np.arange() function is a powerful tool for creating arrays with evenly spaced values. It allows you to define the range of values, the spacing between them, and even the data type of the elements in the resulting array. Knowing how to use np.arange() effectively can greatly enhance your ability to work with numerical arrays in Python.