Skip to content

Effortlessly Master np.arange: A Python Tutorial

CodeMDD.io

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 guess the desired data type based on the other parameters.

Now, let’s explore some examples to get a better understanding of how to use np.arange().

Range Arguments of np.arange()

np.arange() allows you to create arrays with various ranges of values by manipulating its arguments.

Providing All Range Arguments

import numpy as np
# Create an array with values from 0 to 9
arr = np.arange(start=0, stop=10)
print(arr)

Output:

array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In this example, the start parameter is set to 0, the stop parameter is set to 10, and the default step value of 1 is used. As a result, the array contains values from 0 to 9.

Providing Two Range Arguments

import numpy as np
# Create an array with values from 2 to 8 with a step of 2
arr = np.arange(start=2, stop=9, step=2)
print(arr)

Output:

array([2, 4, 6, 8])

In this example, the start parameter is set to 2, the stop parameter is set to 9, and the step parameter is set to 2. As a result, the array contains values from 2 to 8 with a step of 2.

Providing One Range Argument

import numpy as np
# Create an array with values from 0 to 4
arr = np.arange(5)
print(arr)

Output:

array([0, 1, 2, 3, 4])

In this example, only the stop parameter is provided, with a value of 5. The start parameter defaults to 0 and the step parameter defaults to 1. As a result, the array contains values from 0 to 4.

Providing Negative Arguments

import numpy as np
# Create an array with values from 10 to 1 with a step of -1
arr = np.arange(start=10, stop=0, step=-1)
print(arr)

Output:

array([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])

In this example, the start parameter is set to 10, the stop parameter is set to 0, and the step parameter is set to -1. As a result, the array contains values from 10 to 1 with a step of -1.

Counting Backwards

import numpy as np
# Create an array with values from 5 to 1 with a step of -1
arr = np.arange(5, 0, -1)
print(arr)

Output:

array([5, 4, 3, 2, 1])

In this example, the start parameter is set to 5, the stop parameter is set to 1, and the step parameter is set to -1. As a result, the array contains values from 5 to 1 with a step of -1.

Getting Empty Arrays

import numpy as np
# Create an empty array
arr = np.arange(start=5, stop=2, step=1)
print(arr)

Output:

array([], dtype=int64)

In this example, the start parameter is set to 5, the stop parameter is set to 2, and the step parameter is set to 1. Since the start value is greater than the stop value and the step is 1, there are no values to generate an array from.

Data Types of np.arange()

By default, np.arange() will infer the data type of the array based on the input arguments. However, you can explicitly specify the data type using the dtype parameter.

import numpy as np
# Create an array with decimal values
arr = np.arange(start=0, stop=1, step=0.2, dtype=float)
print(arr)

Output:

array([0. , 0.2, 0.4, 0.6, 0.8])

In this example, the start parameter is set to 0, the stop parameter is set to 1, the step parameter is set to 0.2, and the dtype parameter is set to float. As a result, the array contains decimal values from 0.0 to 0.8 with a step of 0.2.

Beyond Simple Ranges With np.arange()

np.arange() can be used to create more complex ranges by combining it with other NumPy functions.

import numpy as np
# Create an array with values exponentially increasing from 1 to 8
arr = 2 ** np.arange(start=1, stop=4, step=1)
print(arr)

Output:

array([2, 4, 8])

In this example, the start parameter is set to 1, the stop parameter is set to 4, and the step parameter is set to 1. We then use the 2 ** prefix to calculate the values as the power of 2. As a result, the array contains values that exponentially increase from 2 to 8.

Comparison of range and np.arange()

While np.arange() is similar to the Python built-in class range, there are some key differences to consider.

Parameters and Outputs

The parameters of range and np.arange() have a similar meaning, but the syntax is slightly different. range accepts three integer arguments (start, stop, step), while np.arange() accepts three numerical arguments (start, stop, step). Additionally, range returns a range object, while np.arange() returns a NumPy array.

Creating Sequences

range can only create sequences of integers, while np.arange() can create sequences of both integers and floats.

Python for Loops

When using range in a Python for loop, it generates the values on the fly without creating an array. This can be more memory-efficient for large ranges. On the other hand, np.arange() creates an array with all the values up front, which might consume more memory.

Overall, np.arange() provides more flexibility and convenient features for creating arrays with numerical ranges compared to range.

Other Routines Based on Numerical Ranges

NumPy provides other routines that are based on numerical ranges and are similar to np.arange(). Some of them are:

  • np.linspace(): Returns evenly spaced values within a specified range.
  • np.logspace(): Returns numbers spaced evenly on a log scale within a specified range.
  • np.geomspace(): Returns numbers spaced evenly on a logarithmic scale (geometric progression) within a specified range.

These routines offer additional functionality for creating arrays with specific numerical ranges.

Quick Summary

  • np.arange() is a NumPy function that creates arrays based on numerical ranges.
  • It accepts parameters (start, stop, step) and returns a NumPy array.
  • The default values for start, step, and dtype are 0, 1, and None respectively.
  • np.arange() can create arrays with different ranges by manipulating its arguments.
  • It can handle both integers and floats as array elements.
  • np.arange() is similar to the Python built-in range, but with additional features and flexibility.
  • NumPy provides other routines based on numerical ranges, such as np.linspace(), np.logspace(), and np.geomspace(), for more specific array creation scenarios.

Conclusion

In this tutorial, you’ve learned how to use np.arange() to create NumPy arrays with numerical ranges. You now have a better understanding of its parameters and how they affect the output. You’ve also seen how np.arange() compares to the Python built-in class range and explored other NumPy routines based on numerical ranges.

Creating NumPy arrays with np.arange() can be useful in various contexts, such as data analysis, scientific computing, and machine learning. With its flexibility and powerful array manipulation capabilities, NumPy allows you to perform complex numerical computations efficiently and effectively.

CodeMDD.io