Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages

NumPy arange() method in Python

Numpy Arange() Method In Python

Introduction

In this tutorial, we are going to discuss the Numpy arange() method in Python. NumPy is a very popular module in Python, mainly used by users for its faster performance and code reliability. It provides a vectorized approach to programming in Python and even makes the code more concise and easier to read.


Numpy arange() Method Basics

Basically, the arange() method in the NumPy module in Python is used to generate a linear sequence of numbers on the basis of the pre-set starting and ending points along with a constant step size.

Syntax,

import numpy as np
np.arange( start , stop , step ,dtype=nome)

Here,

  • start is the starting point of the future generated sequence. The sequence starts with this number,
  • stop is the limit up to which the sequence is to be generated. Note, stop is not included in the sequence itself, only the number before it is considered
  • step is the uniform step size. By default, if nothing is passed as a step, the interpreter considers steps as equal one(1). Remember, step size has to be some non-zero value or else, a ZeroDivisionError would arise.
  • dtype is the type of the resultant ndarray elements. By default, it infers the type from the provided parameters inside the method. The dtype can be none, int or float, etc.

Numpy arange() Example

Let us understand the working of the method Numpy arange() with an example:

import numpy as np

#passing start=1, stop=10, and step=2 and dtype=int
res=np.arange(1,10,2,int)

#printing the result
print("The resultant sequence is : ",res)
#analysing the type of the result
print("Type of returned result is:",type(res))

Output:

Np Arange Example
Np Arange Example

Here,

  • We have initially imported the NumPy module as np for further reference,
  • Then we use the arange() method by passing the respective start, stop, step and dtype arguments as 1, 10, 2, and int to generate an array consisting of integers from 1 to 9 with step=2.
  • When we print the resultant sequence along with the type() of the returned object which turns out to be a member of the ndarray class.

Using Numpy arange() in Python

The arange() method takes four arguments start, stop, step, and the dtype as we saw in the previous section. Now we are going to see how we can use the method in various ways and how it works for all the cases.


1. Using arange() with one argument

When we pass only one parameter to the Numpy arange() method, by default it considers the value to be the stop argument. Take a look at the below-mentioned code example,

import numpy as np

#passing only one parameter to the arange() method
res=np.arange(5)

#printing the result
print("The resultant sequence with one argument : ",res)
#analysing the type of the result
print("Type of returned result is:",type(res))

Output:

The resultant sequence with one argument :  [0 1 2 3 4]
Type of returned result is: <class 'numpy.ndarray'>

Here,

  • As we mentioned earlier, we initially import the numpy module as np,
  • After that, we try to generate a sequence and store it in res, with only one parameter, and that is ‘5‘,
  • We observe the program considers the passed value as the stoping or the endpoint. And creates an array with values [0 1 2 3 4],
  • Again we confirm the type() of the result as ndarray.

2. Using the Numpy arange() without step

When the step parameter is not passed to the arange() method in Python, by default it considers it to have a value 1. Let us look at an example,

import numpy as np

#passing start=5 and stop=8 to arange()
res=np.arange(5,8)

#printing the result
print("The resultant sequence with no step :",res)
#analysing the type of the result
print("Type of returned result is:",type(res))

Output:

The resultant sequence with no step : [5 6 7]
Type of returned result is: <class 'numpy.ndarray'>

So, here we can clearly see that even though we didn’t pass the step parameter, the array created consists of values [5 6 7]. That is, in this case, the default value 1 was used to generate the corresponding output.


3. Using the arange() with negative parameters

So, what if the values passed to the arange() method are negative? It works normally.

If the starting and the ending points are negative, the method generates a sequence in the same way it would have done for positive values. It starts with the start and continues the process by incrementing it with the provided positive step.

Note: If the step provided is negative, then the only difference is going to be the increment part. In that case, the step would be added but since the step value is negative, eventually the array generated is going to be a descending one.

Let us look at an example where we pass negative start and stop values.

import numpy as np

#passing start=-10, stop=-1 and step=3 to arange()
res=np.arange(-10,-1,3)

#printing the result
print("The resultant sequence with negative start and stop :",res)
#analysing the type of the result
print("Type of returned result is:",type(res))

Output:

The resultant sequence with negative start and stop : [-10  -7  -4]
Type of returned result is: <class 'numpy.ndarray'>

As discussed above, the arange() method generates an array consisting of elements [-10 -7 -4] since the provided start and stop parameters were (-10) and (-1), with step= 3.


4. Using Numpy arange() with Python Loops

In the below example we have incorporated the arange() method into the native for loop in Python.

import numpy as np
#to print all even numbers from 2 to nth even number, where n is user input

#user input
n=int(input("Enter the last even number: "))
print("The sequence of even numbers :")

for i in np.arange(2,n+2,2):     #here stop=n+2 so that the nth even number is too printed
    print(i, end=" ")

Output:

Prin Sequence Of Even Numbers
Print Sequence Of Even Numbers

In the above code,

  • The arange() method produces the same output as the built-in range() method. Here, we try to print all the even numbers from 2 to the user-provided last one.
  • np.arange(2,n+2,2) gives us a sequence containing all the numbers starting from 2 to n.
  • As we saw earlier, the arange() method doesn’t include the stop or end value. So, to overcome this situation and to print the last user-provided even value too, we consider the stop parameter as (n+2) with a step=2.

Even though we have used the arange() method with the native for loop in Python, this affects the speed of execution and performance of the code. It becomes slow as well.


Numpy arange() Vs range() in Python

The NumPy module provides us with some really helpful and more importantly, faster methods. In the case of linear sequence generation, the Numpy arange() method outperforms the built-in range() method in terms of performance and speed, even though both perform the same task. This is because of the fact that the numpy module uses vectorized code.


Conclusion

We learned about the arange() method from the NumPy module, how it works, as well as how it is faster and better than the native range() method in Python.


References