Skip to content

Effortlessly Arrange Arrays in Python using np.arrange

[

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.

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 determine the appropriate data type based on the inputs.

Range Arguments of np.arange()

Now that you understand the parameters, let’s look at how to use them to define the range of values in the array created by np.arange().

Providing All Range Arguments

The simplest way to use np.arange() is to provide all the range arguments: start, stop, and step. This allows you to create an array with evenly spaced values between start and stop, incrementing by step:

import numpy as np
arr = np.arange(start=2, stop=10, step=2)
print(arr)
# Output: [2 4 6 8]

In this example, start=2 defines the first value in the array, stop=10 defines the end of the array (exclusive), and step=2 defines the increment between each two consecutive values in the array.

Providing Two Range Arguments

You can also provide only two range arguments: start and stop. If step is omitted, it will default to 1:

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

In this case, step is omitted, so it defaults to 1.

Providing One Range Argument

If you provide only one range argument, it will be interpreted as the stop value, and start will default to 0:

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

In this example, stop=5, so the array will contain values from 0 to 4, incrementing by 1.

Providing Negative Arguments

You can use negative numbers as arguments in np.arange() to create arrays that count backwards:

import numpy as np
arr = np.arange(start=5, stop=0, step=-1)
print(arr)
# Output: [5 4 3 2 1]

In this example, the start value is 5, the stop value is 0 (exclusive), and the step value is -1, so the array counts backwards from 5 to 1.

Counting Backwards

You can even count backwards with positive step values. In this case, start should be greater than stop:

import numpy as np
arr = np.arange(start=5, stop=0, step=1)
print(arr)
# Output: []

In this example, the start value is 5, the stop value is 0 (exclusive), and the step value is 1, but since start is greater than stop, the result is an empty array.

Getting Empty Arrays

If the range of values specified by the arguments doesn’t include any elements, np.arange() will return an empty array:

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

In this example, both start and stop are 0, so the resulting array is empty.

Data Types of np.arange()

By default, np.arange() will generate an array with elements of type int64. However, you can specify a different data type using the dtype argument:

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

In this example, dtype=float specifies that the array should contain elements of type float instead of the default int64.

Beyond Simple Ranges With np.arange()

np.arange() can be used to create arrays with more complex patterns than simple ranges. By combining np.arange() with other NumPy functions, you can create arrays with logarithmic or exponential spacing:

import numpy as np
# Create an array with logarithmic spacing
arr1 = np.logspace(start=1, stop=3, num=10, base=10)
print(arr1)
# Output: [ 10. 16.68100537 27.82559402 46.41588834
# 77.42636827 129.1549665 215.443469 359.38136638
# 599.48425032 1000. ]
# Create an array with exponential spacing
arr2 = np.exp2(np.arange(start=0, stop=5))
print(arr2)
# Output: [ 1. 2. 4. 8. 16.]

In the first example, np.logspace() is used to create an array with logarithmic spacing. The num parameter specifies the number of values in the array, and the base parameter specifies the logarithmic base.

In the second example, np.exp2() is used in combination with np.arange() to create an array with exponential spacing. np.exp2() raises 2 to the power of each value in the array created by np.arange().

Comparison of range and np.arange()

Both the built-in range() function and np.arange() can be used to create sequences of numbers. However, there are some differences between them in terms of parameters and outputs.

Parameters and Outputs

The parameters of range() and np.arange() are similar: start, stop, and step. However, range() returns a range object, while np.arange() returns an array.

# Using range()
range_obj = range(start=0, stop=5, step=1)
print(range_obj)
# Output: range(0, 5)
# Using np.arange()
arr = np.arange(start=0, stop=5, step=1)
print(arr)
# Output: [0 1 2 3 4]

In this example, range_obj is a range object created by range(), while arr is an array created by np.arange().

Creating Sequences

range() is generally used to create sequences of integers, while np.arange() can create sequences of numbers with decimal places as well:

# Using range()
range_seq = list(range(start=0, stop=5, step=1))
print(range_seq)
# Output: [0, 1, 2, 3, 4]
# Using np.arange()
num_seq = np.arange(start=0, stop=5, step=1)
print(num_seq)
# Output: [0 1 2 3 4]

In this example, range_seq is a list created by converting the range object to a list using list(), while num_seq is an array created by np.arange().

Python for Loops

range() is commonly used in Python for loops to iterate over a sequence of integers. However, np.arange() can also be used in Python for loops:

# Using range()
for i in range(start=0, stop=5, step=1):
print(i)
# Output:
# 0
# 1
# 2
# 3
# 4
# Using np.arange()
for i in np.arange(start=0, stop=5, step=1):
print(i)
# Output:
# 0
# 1
# 2
# 3
# 4

In both cases, the for loop iterates over a sequence of numbers and prints each number.

Other Routines Based on Numerical Ranges

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

  • np.linspace(): Creates an array of evenly spaced values within a specified range.
  • np.logspace(): Creates an array of logarithmically spaced values within a specified range.
  • np.geomspace(): Creates an array of geometrically spaced values within a specified range.

These routines can be useful when you need to create arrays with specific spacing patterns.

Quick Summary

In this article, you’ve learned how to use np.arange() to create NumPy arrays with evenly spaced values. You understand the range arguments and how to provide them to specify the range of values in the array. You’ve also seen examples of using positive and negative arguments, as well as providing different data types. Additionally, you’ve explored more advanced usage of np.arange() in combination with other NumPy functions. Finally, you’ve compared range() and np.arange() and seen how they can be used in Python for loops.

Conclusion

np.arange() is a powerful tool for creating arrays with numerical ranges in NumPy. By specifying the range arguments, you can generate arrays with different patterns and spacings. Understanding how to use np.arange() will enable you to work more effectively with NumPy arrays and leverage the power of numerical computing in your Python projects.

Continue your learning journey with NumPy by exploring the related video course, Using NumPy’s np.arange() Effectively. This course will deepen your understanding of np.arange() and provide additional examples and exercises to practice your skills.