How To Use Np.Arange(): A Complete Guide For Beginners (2024)

"

This article is part of in the series

Published: Friday 24th February 2023

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 npprint(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)>>> exampleArrayarray([0, 1, 2])>>> exampleArray.dtypedtype('int64')>>> exampleArray.itemsize # In bytes8

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 npexampleArray = 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 ValueMemoryLimits
np.int88-bit signed integerfrom -128 to 127
np.uint88-bit unsigned integerfrom 0 to 255
np.int1616-bit signed integerfrom -32768 to 32767
np.uint1616-bit unsigned integerfrom 0 to 65535
np.int3232-bit signed integerfrom -2**31 to 2**31-1
np.uint3232-bit unsigned integerfrom 0 to 2**32-1
np.int6464-bit signed integerfrom -2**63 to 2**63-1
np.uint6464-bit unsigned integerfrom 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 bytes4

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.

  1. Home
  2. Python Tips and Tricks
  3. Python Library Tutorials
  4. Python How To's
  5. Python Tutorials

Related Articles

  • Top Python Interview Questions You Should Know the Answer to for a Well-Paying Job
  • How to Use Python’s xrange and Range
  • How to Slice Lists/Arrays and Tuples in Python
  • Installing Python: Detailed Instructions For Windows, Mac, and Linux
  • Pandas Data Frame: A Tutorial for Creating and Manipulating Data
How To Use Np.Arange(): A Complete Guide For Beginners (2024)

FAQs

How to use np arange function? ›

To create an array using np. arange in numpy, you specify the start, stop, and step values, such as array = np. arange(start=0, stop=10, step=2) . This function generates a sequence of numbers within the specified range, which can be incredibly useful in data analysis and scientific computing.

Which function allows you to create a sequence of numbers in the NumPy package? ›

To create sequences of numbers, NumPy provides the arange function which is analogous to the Python built-in range , but returns an array.

What is NumPy array in Python with example? ›

Arrays. 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 are NumPy functions? ›

NumPy functions are used to create, manipulate, and analyze NumPy arrays. The syntax of NumPy functions generally involves calling the function and passing one or more parameters, such as the shape of the array, the range of values to generate, or the type of data to use.

How do you use NP full in Python? ›

full() in Python. numpy. full(shape, fill_value, dtype = None, order = 'C') : Return a new array with the same shape and type as a given array filled with a fill_value.

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 NumPy array and list with example? ›

The main difference is that NumPy arrays are much faster and have strict requirements on the hom*ogeneity of the objects. For example, a NumPy array of strings can only contain strings and no other data types, but a Python list can contain a mixture of strings, numbers, booleans and other objects.

What is the purpose of the NumPy arange function? ›

Introduction. The numpy. 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.

What is the main object of NumPy? ›

NumPy's main object is the hom*ogeneous multidimensional array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of non-negative integers. In NumPy dimensions are called axes.

Which function is used to create a NumPy array? ›

The array object in NumPy is called ndarray . We can create a NumPy ndarray object by using the array() function.

How do you create a NumPy array with the integers from 0 to 9? ›

For instance, numpy. arange(10) creates 10 values of integers from 0 to 9.

How can you combine two NumPy arrays column-wise? ›

In NumPy, you can join 2 or more arrays together using np. concatenate . To do so, you will need to ensure that if you are adding a row, the rows of both arrays must be the same. Likewise for columns.

Top Articles
Latest Posts
Article information

Author: Annamae Dooley

Last Updated:

Views: 6191

Rating: 4.4 / 5 (65 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Annamae Dooley

Birthday: 2001-07-26

Address: 9687 Tambra Meadow, Bradleyhaven, TN 53219

Phone: +9316045904039

Job: Future Coordinator

Hobby: Archery, Couponing, Poi, Kite flying, Knitting, Rappelling, Baseball

Introduction: My name is Annamae Dooley, I am a witty, quaint, lovely, clever, rich, sparkling, powerful person who loves writing and wants to share my knowledge and understanding with you.