np.arange() - How To Use the NumPy arange() Method

NumPy is a Python library widely considered to be the most important library for numerical computing.

Within NumPy, the most important data structure is an array type called np.array().

NumPy contains a number of methods that are useful for creating boilerplate arrays that are useful in particular circumstances. One of these methods is np.arange().

In this article, I will teach you everything you need to know about the np.arange() method. By the end of this article, you will know np.arange()'s characteristics, uses, and properties, and will feel comfortable integrating this method into your Python applications.

Table of Contents

You can use the links below to navigate to a particular section of this tutorial:

How To Import NumPy

To use the np.arange() method, you will first need to import the NumPy library into your Python script. You can do this with the following code:

import numpy as np

Now that this import has been completed, we are ready to start learning about the np.arange() method!

Click here to return to the Table of Contents

How to Use The Np.arange() Method

To start, let's discuss how to use NumPy's np.arange() method.

The np.arange() method creates a very basic array based on a numerical range that is passed in by the user.

More specifically, a basic form of the np.arange() method takes in the following arguments:

  • start: the lowest value in the outputted NumPy array
  • stop the highest value (exclusive) from the outputted NumPy array

The output of the np.arange() method is a Numpy array that returns every integer that is greater than or equal to the start number and less than the stop number.

To be specific, the np.arange() method includes the lower endpoint but excludes the lower endpoint.

Let's consider a few examples:

np.arange(0,10)

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

np.arange(-5,5)

#Returns array([-5, -4, -3, -2, -1,  0,  1,  2,  3,  4])

np.arange(0,0)

#Returns array([], dtype=int64)

It is possible to run the np.arange() method while passing in a single argument. In this case, the np.arange() method will set start equal to 0, and stop equal to the number that you pass in as the sole parameter.

Single-argument np.arange() methods are useful for creating arrays with a desired length, which is helpful in writing loops (we'll explore this more later).

A few examples of single-argument np.arange() methods are below:

np.arange(1)

#Returns array([0])

np.arange(5)

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

np.arange(10)

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

The np.arange() method also accepts optional third and fourth arguments: step and dtype. We will explore both of these parameters next.

Click here to return to the Table of Contents

The np.arange() Method's step Argument

NumPy's np.arange() method accepts an optional third argument called step that allows you to specify how much space should be between each element of the array that it returns. The default value for step is 1.

As an example, let's consider the np.arange() method that generates a NumPy array of all the integers from 0 to 9 (inclusive):

np.arange(0,10)

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

If we wanted to generate the same list but only include elements that had a space of 5 integers between them, we could specify step=5:

np.arange(0,10, step=5)

#Returns array([0, 5])

In fact, you do not need to actually specify the step= component of the argument. The following code generates the same output:

np.arange(0,10, 5)

#Returns array([0, 5])

Click here to return to the Table of Contents

Data Types and the Np.arange() Method

NumPy's np.arange() method accepts an optional fourth argument called dtype that allows you to specify the type of data contained in the NumPy array that it generates. Since dtype is optional, it is fine to omit it from the np.arange() method.

The default value for dtype is None. This means that when you do not specify a value for dtype, then the np.arange() method will attempt to deduce what data type should be used based on the other three arguments.

Before diving into how the np.arange() method determines data types when they are not specified, there is one very important concept you should understand about how NumPy arrays work.

All of the elements in a NumPy array must be of the same data type. So an array cannot contain both floating-point numbers and integers. It must have all floating-point numbers or all integers.

This common data type is also referred to as dtype and can be accessed as an attribute of the array object using the dot operator.

As an example, if we run the following code:

my_array = np.arange(0,10)

print(my_array.dtype)

Then Python will print int64, which is the value of dtype for the NumPy array.

NumPy has several different values for dtype that are available ot users. Here are a few examples for integers specifically:

  • np.int8: a signed integer with 8 bits
  • np.uint8: an unsigned integer with 8 bits
  • np.int16: a signed integer with 16 bits
  • np.uint16: an unsigned integer with 16 bits

If you're interested in learning more about the data types available within NumPy, please read their documentation page to learn more.

Click here to return to the Table of Contents

How To Count Backwards With NumPy's np.arange() Method

It is possible to use NumPy's np.arange() method to create a NumPy array that lists its elements in descending order (instead of ascending order, which is the default). This section will show you how.

We have created NumPy arrays whose elements are in ascending order by listing a smaller number following by a larger number, like this:

np.arange(0,10)

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

To create a NumPy array whose elements are listed in descending order, all we need to do is list the elements backwards and specify a negative value for the step argument! Here is an example:

np.arange(10,0, -1)

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

We can also use this strategy while specifying a value for the dtype argument. Here is an example:

np.arange(10,0, -1, dtype='int64')

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

Click here to return to the Table of Contents

How To Generate Empty NumPy Arrays With np.arange()

There are certain cases where you will want to generate empty NumPy arrays. It is possible to do this using NumPy's np.arange() method.

First let's talk about why you might want an empty NumPy array. As an example, consider the situation where you are storing transaction history in a NumPy array before inserting it into a database. In this case, you'd want to begin with an empty array and add to it over time.

The NumPy np.arange() method allows you to easily generate empty NumPy arrays. To do this, all that is required is for you to list the same number twice.

A few examples are below:

np.arange(1,1)

#Returns array([], dtype=int64)

np.arange(1.5, 1.5)

#Returns array([], dtype=float64)

The reason this returns an empty array is because the np.arange() method is designed to exclude the upper endpoint (which, in this case, is actually equal to the lower endpoint).

Click here to return to the Table of Contents

How To Create Tuples Using NumPy's np.arange()

While NumPy's np.arange() method is primarily used to create NumPy arrays, it is also possible to use np.arange() to create other data structures. I'll show you how to create tuples using np.arange() in this section.

First, let's create a basic NumPy array using the np.arange() method:

np.arange(0,10)

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

If we wrap this NumPy array in Python's built-in tuples function, we can easily turn this array into a tuple!

tuple(np.arange(0,10))

#Returns (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

You can wrap this new data structure in a type function to make sure that it is indeed a tuple:

type(tuple(np.arange(0,10)))

#Returns 'tuple'

Click here to return to the Table of Contents

How To Create Sets Using NumPy's np.arange()

In the last section, I showed you how to create Python tuples using NumPy's np.arange() method. We will see in this section that the strategy for creating Python sets using NumPy's np.arange() method is quite similar.

First, create a NumPy array using np.arange():

np.arange(1, 10)

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

Then, just like we did when learning about tuples, we'll wrap the entire NumPy array in a set() function:

set(np.arange(1, 10))

#Returns {1, 2, 3, 4, 5, 6, 7, 8, 9}

As before, we can wrap this new data structure in a type function to make sure that it is indeed a set:

type(set(np.arange(0,10)))

#Returns set

Click here to return to the Table of Contents

How To Use Numpy's np.arange() Method To Write Loops

One of the more common use cases for NumPy's np.arange() method is to create arrays of integers to loop over in a for loop. In this section, I will demonstrate how to use np.arange() to write loops using two examples.

In a for loop, you can use the np.arange() method by placing it after the in keyword, like this:

number = 1 

for x in np.arange(10):

    number *= x

print(number)

#Returns 0, since 0 is an element of np.arange(10) and multiplies number variable to 0 on the first loop

In the code above, we loop over the array object array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) and multiply each element against the number variable.

Let's consider another example:

for x in np.arange(0, 100, 5):

    print(x)

#Returns every integer that is a multiple of 5 between 0 and 100 (excluding 100)

Click here to return to the Table of Contents

The Differences Between Python's Built-In Range Function and NumPy's np.arange() Method

So far in this article, I have performed a deep dive into the capabilities of NumPy's np.arange() method.

Anyone who has done much Python programming before may notice that np.arange() is quite similar to Python's built-in range() function.

Because of this, I will conclude this article by providing a comparison of the range() function and the np.arange() method.

The first - and most obvious - difference between range() and np.arange() is that the former is a built-in Python function, while the latter comes with NumPy. Because of this, you can't use np.arange() unless you've already imported the NumPy numerical computing library.

Second, let's compare what their outputs look like. When you run the built-in range method, you get a special range class:

range(0, 10)

#Returns range(0,10)

type(range(0, 10))

#Returns 'range')

This is different from np.arange(), which returns a NumPy array (as we've seen many times in this tutorial).

Lastly, let's compare their parameters. Both functions accept the start, stop, and step arguments, which is one important commonality. However, range() has an important limitation - it can only work with integers! If you pass in any other data type, you will get a TypeError.

Click here to return to the Table of Contents

Final Thoughts

After reading this tutorial, you should have a firm understanding of how to use NumPy's np.arange() method. This is one of the fundamental NumPy methods used by Python developers, so please feel free to return back to this lesson if you ever get stuck!


Written on April 25th, 2020