"
This article is part of in the series

codes on screen

NumPy is one of the best-known components of the standard Python library, popular because it makes numerical computing easy. The library offers several array creation routines, and the arange() function is one of them. 

It is referred to as np.arange() and is based on numerical ranges. The "np" represents the NumPy module in the Python library.

Writing NumPy arrays is essential since several other modules in the standard Python library rely on them. Pandas, scikit-learn, Pandas, and SciPy are a few popular modules that demand the use of these arrays. 

This brief guide explains what np.arange() is and how you can use it to work with arrays. 

np.arange(): Return Value and Parameters 

The function is one of many array creation routines. The function generates a ndarray instance with evenly spaced values before returning a reference to it. So, it essentially works on the basis of ranges. 

You can use four parameters with arange():

numpy.arange([start, ]stop, [step, ], dtype=None) -> numpy.ndarray

These parameters enable you to define the interval of values in the array, how much space there is between them, and what type they are.

The start parameter defines the value in the array's first index, and it cannot be zero. If you supply zero as the value, Python will throw a ZeroDivisionError. Moving away from the start value becomes impossible if the increment or decrement is zero.

As you might have guessed, the stop parameter defines the value in the final index of the array. This number isn't included in the array – the number before it may be the final number in the array (see example below). 

The step parameter defines the difference between the array's consecutive values. By default, the values are spaced by one. The dtype parameter defines the type of elements of the array. By default, it is "None." 

If you don't supply a value in the dtype parameter, the arange() function will determine the types of array elements based on the start, stop, and step parameters.

The official documentation is the best source of detailed information about the arrange() function's parameters and return value. 

np.arange(): Range Arguments

The function uses the parameters to define the values inside the array it creates. So, you must pass a minimum of one argument for it to work.

Let's say you want to create a NumPy routine. Begin by importing the NumPy module from the standard library:

>>> import numpy as np

You can now use the arange() function, like so:

>>> print(np.arange(start=2, stop=7, step=2))
[2 4 6]

The start value is two, so the first element of the returned array is two. The step value is also two, making the second value four and the third value six. 

Following this pattern, the next value would be eight, but since the stop value is seven, the returned array has only three elements. 

The nice thing about arange() is that you can pass the start, stop, and step values as positional values, like so:

import numpy as np
print(np.arange(2, 7, 2))

This code is equivalent to the previous example and returns identical results. The result of the code would be the same if the stop parameter were changed from seven to eight. 

This is because the stop parameter must be greater than eight for eight to be included in the array. 

Interestingly, besides changing the stop value to nine, you can introduce a decimal point to change the stop value.

>>> print(np.arange(2, 8.1, 2))
[2. 4. 6. 8.]

Unlike the previous example, the code above creates an array of floating-point numbers. This won't happen if you define dtype. We explore in the final leg of this guide.

Supplying Two Range Arguments

The arange() function can work without the step parameter:

>>> print(np.arange(start=2, stop=8, step=1))
[2 3 4 5 6 7]
>>> print(np.arange(start=2, stop=8))
[2 3 4 5 6 7]

As you can see, the two statements we executed are equivalent. This is because the step value defaults to one. There's another way to write the same statement:

>>> print(np.arange(2, 8))
[2 3 4 5 6 7]

When supplying two positional arguments, bear in mind that the first is "start" and the second is "stop."

Supplying a Single Range Argument

As mentioned earlier, the arange() function needs at least one argument to work – the stop argument. 

When you use the function with only the stop argument, it will count from zero to the supplied value. The value of "step" will be one, which is the default value. 

>>> print(np.arange(8))  
[0 1 2 3 4 5 6 7]

So, supplying one argument to the arange() function works the same way as when the start value is zero. Bear in mind that if you explicitly define stop without start, you will encounter a TypeError:

>>> np.arange(stop=8)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: arange() missing required argument 'start' (pos 1)

The arange() function doesn't allow the explicit declaration of the stop value without the start value. If you want to provide a single value to arange() explicitly, it expects it to be the start value. 

Supplying Negative Arguments

The step value is positive by default, so you can provide negative start and stop values:

>>> print(np.arange(-8, -2))
[-8 -7 -6 -5 -4 -3]
>>> print(np.arange(-5, -2, 2))
[-5 -3]

Counting Backwards

When a negative step value is supplied, the array holds values counting backwards from start to stop. So, the start value has to be greater than the stop value:

>>> print(np.arange(8, 2, -1))
[8 7 6 5 4 3]

np.arange(): The dtype Parameter

The dtype parameter allows you to define the type of elements in the array. Any element in a NumPy array is of the same type – dtype – which is short for "data type."

dtype allows better control over size and precision than Python's built-in numeric types. NumPy dtypes have aliases similar to Python's built-in types but are distinct from Python's built-in data types. 

NumPy routines can work with Python's numeric types, and the reverse is also true. More interestingly, some dtypes have platform-dependent definitions. You can explore the depths of the workings of dtypes in the official documentation. 

If you refrain from defining dtype, the arange() function will determine the dtype of the resulting array based on the supplied value(s).

>>> exampleArray = np.arange(3)
>>> exampleArray
array([0, 1, 2])
>>> exampleArray.dtype
dtype('int64')
>>> exampleArray.itemsize  # In bytes
8

In the arange() function above, a single "int" type argument defines the range of values. So, the array defines the dtype of the array as an integer type, which in this case is the int64 dtype. It is a 64-bit integer type, which is why we get 8 bytes when we use .itemsize.

So, the code above would be the same as declaring dtype to be int:

import numpy as np
exampleArray = np.arange(3, dtype=int)
print(exampleArray)
print(exampleArray.dtype)

Bear in mind that the argument dtype=int doesn't refer to the int datatype in Python. It either means int64 or np.int. 

NumPy comprises several fixed-size integer dtypes, all of which have different limits and memory:

dtype Value Memory Limits
np.int8 8-bit signed integer from -128 to 127
np.uint8 8-bit unsigned integer from 0 to 255
np.int16 16-bit signed integer from -32768 to 32767
np.uint16 16-bit unsigned integer from 0 to 65535
np.int32 32-bit signed integer from -2**31 to 2**31-1
np.uint32 32-bit unsigned integer from 0 to 2**32-1
np.int64 64-bit signed integer from -2**63 to 2**63-1
np.uint64 64-bit unsigned integer from 0 to 2**64-1

 

You can define any of these dtypes when using the arange() function:

>>> import numpy as np
>>> exampleArray = np.arange(3, dtype=np.int32)
>>> print(exampleArray)
[0 1 2]
>>> print(exampleArray.dtype)
int32
>>> print(exampleArray.itemsize) # In bytes
4

The array is the same as in the previous example, but the size of the elements is set to four bytes. 

If you supply a decimal number as an argument to arange(), the dtype will be a NumPy floating-point type:

>>> exampleArray = np.arange(5.0)
>>> print(exampleArray)
[0. 1. 2. 3. 4.]
>>> print(exampleArray.dtype)
float64
>>> print(np.arange(1, 3.1))
[1. 2. 3.]

In the final statement above, you will notice that though the start value is an integer, the dtype is np.float64. This is because the stop value is a floating point number. The same would happen if the step value were a floating point number. 

To set float64 as the dtype explicitly, you can run:

>>> exampleArray = np.arange(5, dtype=float)
>>> print(exampleArray)
[0. 1. 2. 3. 4.]
>>> print(exampleArray.dtype)
float64

So, setting float as the dtype sets it to np.float or float64. Remember, this is a dtype and not the Python float. 

You can also specify "np.float32" as the dtype to store values in a smaller size in exchange for lower precision. The elements in np.float32 arrays are each four bytes in size. You can check this using the .itemsize parameter.

The sizes of these variables become important when using tools such as TensorFlow and also when working with images.Â