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)
Top Articles
How small changes to our diet can benefit the planet
How to reduce climate change by changing your food habits at every meal
jazmen00 x & jazmen00 mega| Discover
Shoe Game Lit Svg
Dlnet Retiree Login
Craigslist Niles Ohio
Citibank Branch Locations In Orlando Florida
Occupational therapist
Manhattan Prep Lsat Forum
Ixl Elmoreco.com
Fort Carson Cif Phone Number
Kansas Craigslist Free Stuff
The Potter Enterprise from Coudersport, Pennsylvania
Citi Card Thomas Rhett Presale
Over70Dating Login
Anki Fsrs
Mercy MyPay (Online Pay Stubs) / mercy-mypay-online-pay-stubs.pdf / PDF4PRO
Washington, D.C. - Capital, Founding, Monumental
People Portal Loma Linda
Flower Mound Clavicle Trauma
111 Cubic Inch To Cc
Harem In Another World F95
Dirt Removal in Burnet, TX ~ Instant Upfront Pricing
Vintage Stock Edmond Ok
Schedule 360 Albertsons
Craigslist Maui Garage Sale
Satisfactory: How to Make Efficient Factories (Tips, Tricks, & Strategies)
Invitation Homes plans to spend $1 billion buying houses in an already overheated market. Here's its presentation to investors setting out its playbook.
Great Clips Grandview Station Marion Reviews
Used Patio Furniture - Craigslist
Belledelphine Telegram
Rugged Gentleman Barber Shop Martinsburg Wv
Relaxed Sneak Animations
Top 20 scariest Roblox games
Co10 Unr
Ilabs Ucsf
Tmj4 Weather Milwaukee
Chase Bank Cerca De Mí
Greencastle Railcam
Solemn Behavior Antonym
My.lifeway.come/Redeem
Toth Boer Goats
“Los nuevos desafíos socioculturales” Identidad, Educación, Mujeres Científicas, Política y Sustentabilidad
Ross Dress For Less Hiring Near Me
Linkbuilding uitbesteden
Haunted Mansion Showtimes Near Millstone 14
Meee Ruh
Jeep Forum Cj
Dolce Luna Italian Restaurant & Pizzeria
2000 Fortnite Symbols
Itsleaa
Latest Posts
Article information

Author: Greg Kuvalis

Last Updated:

Views: 5949

Rating: 4.4 / 5 (75 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Greg Kuvalis

Birthday: 1996-12-20

Address: 53157 Trantow Inlet, Townemouth, FL 92564-0267

Phone: +68218650356656

Job: IT Representative

Hobby: Knitting, Amateur radio, Skiing, Running, Mountain biking, Slacklining, Electronics

Introduction: My name is Greg Kuvalis, I am a witty, spotless, beautiful, charming, delightful, thankful, beautiful person who loves writing and wants to share my knowledge and understanding with you.