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.

What does the np arange 5 15 2 function in NumPy do? ›

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 difference between range() and arange() functions in Python? ›

arange store each individual value of the array while range store only 3 values (start, stop and step). That's the reason arange is taking more space compared to range . As the question is about the size, this will be the answer.

How to use full function in 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. Parameters : shape : Number of rows order : C_contiguous or F_contiguous dtype : [optional, float(by Default)] Data type of returned array.

What does NP where () do in Python? ›

Numpy. where is a powerful tool for conditional element selection or transformation on NumPy arrays. It is commonly used in data processing, analysis, and algorithms. In this tutorial, we look at how you can use the numpy.

Is NP arange faster than range? ›

arange(start=0.2, stop=0.5, step=0.1, dtype=float) will generate a NumPy array, array([0.2, 0.3, 0.4]).) Here comes the performance part. For a large program, we do care about the speed of our code. Generally speaking, arange performs faster than range , given the data size is large.

What is the purpose of range () function? ›

Definition and Usage

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.

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

arange() for when you have a desired step size. linspace() for when you have a desired number of values.

How to include endpoint in NP arange? ›

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.

How do you use range in Python example? ›

The most common form is range(n) , for integer n, which returns a numeric series starting with 0 and extending up to but not including n, e.g. range(5) returns 0, 1, 2, 3, 4 . Or put another way, range(n) returns a series of n numbers, starting with 0`.

How do you pick a random number in a NumPy range? ›

To generate a random integer, we use the random module from NumPy. Using the numpy random randint() function, we can generate a random integer from a range of 0 to a number of our choice. Let us generate a random number between 0 and 12 using the numpy random randint() function.

How do you use the NP array function? ›

Important Numpy Functions in Python
  1. np. array(): This function is used to create an array in NumPy. Example Code: import numpy as np arr = np.array([1, 2, 3]) print(arr) ...
  2. np. arange(): This function is used to create an array with a range of values. ...
  3. np. zeros(): This function is used to create an array filled with zeros.
Mar 2, 2023

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.

What does NP sort () do? ›

Return a sorted copy of an array.

How to assign NumPy array to list? ›

With NumPy, np. array objects can be converted to a list with the tolist() function. The tolist() function doesn't accept any arguments. If the array is one-dimensional, a list with the array elements is returned.

References

Top Articles
Latest Posts
Article information

Author: Greg O'Connell

Last Updated:

Views: 5680

Rating: 4.1 / 5 (42 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Greg O'Connell

Birthday: 1992-01-10

Address: Suite 517 2436 Jefferey Pass, Shanitaside, UT 27519

Phone: +2614651609714

Job: Education Developer

Hobby: Cooking, Gambling, Pottery, Shooting, Baseball, Singing, Snowboarding

Introduction: My name is Greg O'Connell, I am a delightful, colorful, talented, kind, lively, modern, tender person who loves writing and wants to share my knowledge and understanding with you.