NumPy arange(): Complete Guide (w/ Examples) • datagy (2024)

In this guide, you’ll learn how to use the NumPy arange function to create a sequence of numbers. This guide will teach you everything you need to know – including how the function can be customized to meet your needs. NumPy provides a number of different functions to create arrays, such as the np.linspace() function and the np.zeros() function.

Understanding how to work with arrays and how to generate them on the fly is an important skill for any data analyst or data scientist. Because NumPy is so important to other data science libraries, such as Pandas and Scikit-Learn, it’s important to understand how it works.

By the end of this tutorial, you’ll have learned:

  • How to use the NumPy arange() function to create sequences of numbers
  • How to customize the function to count backward or create negative numbers
  • How to modify the data types of the NumPy arange() function
  • How to generate 2-dimensional arrays using the NumPy arange() function
  • How the NumPy arange() function compares to other functions

Table of Contents

Understanding the NumPy arange() Function

In this section, you’ll learn how to use the NumPy arange() function to generate a sequence of numbers. We’ll start by taking a look at the parameters of the function and the default arguments that the function provides. Then, we’ll create our first array with the function:

# Understanding the NumPy arange() Functionnp.arange([start, ]stop, [step, ]dtype=None, *, like=None)

From the code block above, you can see that the function offers five different parameters. The table below describes the parameters and their default arguments:

ParameterDescriptionDefault ArgumentAccepted Values
start=The starting value of the interval, which is included.0integer, real value
stop=The end of the interval, which is not included.N/Ainteger, real value
step=Spacing between the values. If step is provided as a position argument, start must also be provided.1integer, real value
dtype=The type of the output array. If none is provided, then the data type is inferred.Nonedtype
like=Reference object to allow the creation of arrays which are not NumPy arrays.Nonearray-like

Now that you have a strong understanding of all of the different parameters of the NumPy arange function, let’s start looking at how you can create a sequence of numbers.

Using NumPy arange to Create a Sequence of Number

The NumPy arange() function has only a single required parameter: the stop parameter. By default, NumPy will start its sequences of values beginning at 0 and increasing by 1. When you pass in a single number, the values will increase from 0, up to (but not including) the value, incrementing by 1.

Let’s see how we can create an array of values from 0 to 4:

# Creating a Sequence of Numbers Using NumPy arange()import numpy as nparr = np.arange(5)print(arr)# Returns: [0 1 2 3 4]

We can see that function returns the actual array. This means that the values are generated when the function is run. Let’s see how we can customize the array that’s generated by changing the start value.

Customizing the Start Value Using NumPy arange

By default, the NumPy arange() function will start at 0 and continue up to the specified stop value (though not include it). You can modify the starting value of the resulting array by passing a value into the start= parameter.

Let’s see how we can create an array that goes from 5 through 9 using the NumPy arange function:

# Modifying the Start Value When Creating Arrays Using NumPy arange()import numpy as nparr = np.arange(5, 10)print(arr)# Returns: [5 6 7 8 9]

In the code example above, we specified the arguments positionally. However, we can also use keyword arguments to make our code more explicit:

# Modifying the Start Value Using Keyword Argumentsimport numpy as nparr = np.arange(start=5, stop=10)print(arr)# Returns: [5 6 7 8 9]

In the following section, you’ll learn how to customize the step value used when creating arrays.

Customizing the Step Value Using NumPy arange

By default, NumPy will increment the value of the array by 1. However, you can customize this behavior by passing a value into the step= parameter. Because NumPy allows you to use data types for its ranges, we can create ranges that accept floating point values.

Let’s create an array that goes from 0 to 10 and increases by 1.5:

# Creating Arrays with Different Step Valuesimport numpy as nparr = np.arange(0, 10, 1.5)print(arr)# Returns: [0. 1.5 3. 4.5 6. 7.5 9. ]

In the code above, we declared 0 (even though it’s the default value). This is necessary unless we specify the stop and step arguments using keyword arguments. Let’s see what this looks like:

# Creating Arrays with Different Step Values Using Keyword Argumentsimport numpy as nparr = np.arange(stop=10, step=1.5)print(arr)# Returns: [0. 1.5 3. 4.5 6. 7.5 9. ]

In the following section, we’ll explore the differences between the Python range() function and the NumPy arange() function.

Differences Between NumPy arange and Python range()

On the surface, the NumPy arange() function does very similar things compared to the Python range() function. However, there are a few notable differences. Let’s take a look at the key differences:

  • NumPy arange() generates the array while Python range() generates lazily. The values in NumPy arange are generated, which may use more memory. However, if the values need to be accessed multiple times, then this can be more efficient.
  • NumPy arange() can work with floating point values. The Python range() function can only work with integer data types. However, the NumPy arange() function can work with different numeric data types.
  • Python range() is faster when using the range to iterate using for-loops. Because the Python range() function generates items only as needed, it can be used for for loops with better efficiency.

Understanding these key differences allows you to make informed decisions in terms of when to use which function.

Creating Sequences Backwards with NumPy arange

The NumPy arange() function also allows you to pass in negative step values. This allows you to create a sequence of numbers that moves backward. This allows you to decrement over a sequence. Let’s see how we can create the values from 5 to 1, decreasing by 1:

# Creating a Sequence Backwards with NumPy arange()import numpy as nparr = np.arange(5, 0, -1)print(arr)# Returns: [5 4 3 2 1]

In the following section, you’ll learn how to customize the data types of the resulting arrays.

Customizing Data Types in NumPy arange

By default, NumPy will infer the data type of the array it generates. Depending on the type of start, stop, or step value that you pass in, NumPy will infer what the best data type to use is. However, there may be cases when you want to specify which data type to use.

NumPy provides a number of different data types, such as float and int. To learn more about these data types, check out the official documentation here.

Let’s see how NumPy will infer data types based on the requirements of the function:

# Infering Data Types as Floatsimport numpy as nparr = np.arange(0, 10, 1.5)print(arr)# Returns: [0. 1.5 3. 4.5 6. 7.5 9. ]

If you want to specify the specific data type, you can use the dtype= parameter to pass in a data type. Let’s see how we can specify that we want to use float16 as the data type:

# Specifying the Data Type of NumPy arange()import numpy as nparr = np.arange(0, 10, 1.5, dtype='float16')print(arr)# Returns: [0. 1.5 3. 4.5 6. 7.5 9. ]

In the following section, you’ll learn how to create 2-dimensional arrays with the NumPy arange function.

Creating 2 Dimensional Arrays with NumPy arange

By default, NumPy will create a 1-dimension array when using the arange() function. However, we can chain the .reshape() method to create an array of any dimension.

Let’s see how we can accomplish this using Python and NumPy:

# Creating a 2D Array with NumPy arange()import numpy as nparr = np.arange(10).reshape(2, 5)print(arr)# Returns: # [[0 1 2 3 4]# [5 6 7 8 9]]

This can be extended to create arrays of even more complex dimensions.

Frequently Asked Questions

What does the NumPy arange() function do?

The NumPy arange() function creates a sequential array, allowing you to specify the start, stop, and step values. By default, NumPy will start at 0 and increase values by -1.

How is NumPy arange() different from Python range()?

The NumPy arange function has three main differences compared to the Python range function: (1) it generates the array, rather than lazy-generating values, (2) it allows for different data types (such as floats), and (3) it can perform more slowly compared when iterating using a for loop.

How is NumPy arange() different from NumPy linspace()?

The NumPy linspace function creates an evenly spaced array between two values, by calculating the step on the fly. The NumPy arange function specifies the step value (rather than the number of elements).

When should you use NumPy arange() over Python range()?

NumPy arange() allows you to use data types beyond integers and generates the array when the function is executed. However, the function is also less memory efficient compared to the range() function, unless items are required more than once.

Conclusion

In this tutorial, you learned how to use the NumPy arange() function to generate a sequence of numbers. You first learned how the function works and how it can be customized using its various parameters. Then, you learned how to generate sequences, specifying the start, stop, and step parameters. From there, you learned how to use the function creatively to specify data types and create 2D arrays.

Additional Resources

To learn more about related topics, check out the tutorials below:

  • Python range(): A Complete Guide w/ Examples
  • NumPy linspace: Creating Evenly Spaced Arrays with np.linspace
  • NumPy Zeros: Create Zero Arrays and Matrix in NumPy
  • Indexing and Slicing NumPy Arrays: A Complete Guide
  • Flatten an Array with NumPy flatten
  • NumPy arange: Official Documentation
NumPy arange(): Complete Guide (w/ Examples) • datagy (2024)

FAQs

What is arange () in NumPy? ›

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() : Python.

What is the difference between range() and arange() functions in Python? ›

range is a built-in function in Python, while arange is a function in NumPy package. They basically do the exact same thing. If you don't know how to use them, check out either the article of range(Python) or arange(NumPy).

What will w shape tell you about NumPy array w? ›

To determine the shape of a NumPy array, you can utilize the shape attribute, which provides a tuple representing the number of rows and columns. For instance, a 3x4 array will yield a shape of (3, 4) . The shape attribute is essential for understanding array dimensions and enabling diverse operations.

What is the meaning of NP array in Python? ›

A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension.

What does arrange() do in Python? ›

arange() function in Python is a powerful tool that allows you to create arrays with evenly spaced values. It is a versatile function used in various scenarios, from simple arithmetic to complex mathematical operations.

Does NP Arange include an endpoint? ›

numpy. arange relies on step size to determine how many elements are in the returned array, which excludes the endpoint. This is determined through the step argument to arange . The arguments start and stop should be integer or real, but not complex numbers.

What is the difference between linspace and arange in NumPy? ›

arange: It generates values with a specified step size between the start and stop values, similar to Python's built-in range function. linspace: It generates values with a specified number of points evenly spaced between the start and stop values (inclusive).

What is the most important object defined in NumPy array? ›

Answer. Answer: The most important object defined in NumPy is an N-dimensional array type called ndarray.

What is a correct method to split arrays? ›

Use the array_split() method, pass in the array you want to split and the number of splits you want to do.

How does NumPy reshape arrays? ›

You can think of reshaping as first raveling the array (using the given index order), then inserting the elements from the raveled array into the new array using the same kind of index ordering as was used for the raveling.

Are NumPy arrays faster than lists? ›

Because the Numpy array is densely packed in memory due to its hom*ogeneous type, it also frees the memory faster. So overall a task executed in Numpy is around 5 to 100 times faster than the standard python list, which is a significant leap in terms of speed.

What is the difference between array and NumPy array in Python? ›

The main difference is that NumPy arrays are much faster and have strict requirements on the hom*ogeneity of the objects. Both lists and NumPy arrays have a wide array of built-in methods for performing a variety of tasks including sorting, finding min/max, truncating, appending, concatenating and much more.

What is a correct syntax to return the shape of an array? ›

The ma. shape() method in the NumPy module in Python is used to obtain the shape of a given array. The shape of an array is the number of elements found in each axis (rows and columns) of the array.

Why is NumPy called arange? ›

The arrayrange() function is similar to the range() function in Python, except that it returns an array as opposed to a list. arange() is a shorthand for arrayrange() . Tellingly, there is another example with array(range(25)) (p. 16), which is functionally the same as arrayrange() .

Does NumPy arange include endpoint? ›

The endpoint can be included by setting the third parameter of np. arange to False, which will create a sequence of numbers up to but not including the endpoint. Alternatively, if the third parameter is set to True, the endpoint will be included in the sequence. This parameter is optional and defaults to False.

What is a grid in NumPy? ›

The numpy. meshgrid function is used to create a rectangular grid out of two given one-dimensional arrays representing the Cartesian indexing or Matrix indexing. Meshgrid function is somewhat inspired from MATLAB. Consider the below figure with X-axis ranging from -4 to 4 and Y-axis ranging from -5 to 5.

Top Articles
Latest Posts
Article information

Author: Kareem Mueller DO

Last Updated:

Views: 6193

Rating: 4.6 / 5 (66 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Kareem Mueller DO

Birthday: 1997-01-04

Address: Apt. 156 12935 Runolfsdottir Mission, Greenfort, MN 74384-6749

Phone: +16704982844747

Job: Corporate Administration Planner

Hobby: Mountain biking, Jewelry making, Stone skipping, Lacemaking, Knife making, Scrapbooking, Letterboxing

Introduction: My name is Kareem Mueller DO, I am a vivacious, super, thoughtful, excited, handsome, beautiful, combative person who loves writing and wants to share my knowledge and understanding with you.