np.arange vs range: The Complete Guide in 2022

Arrays are not native data types in Python. To use an array in Python, we need to use the numpy library. For large arrays, a vectorized numpy operation is the fastest.

np.arange

The np.arange() function returns an array with evenly spaced elements as per the interval. To use the np.arange() method in your Python script, you have to import a Numpy library.

import numpy as np

Let’s see the syntax of numpy arange() method.

Syntax

numpy.arange(start, stop, step, dtype=None)

Example

import numpy as np

arr = np.arange(start=0, stop=11, step=2)
print(arr)

Output

[ 0 2 4 6 8 10]

You can see that we got the evenly spaced array elements in the output.

The np.arange() method includes the start value but excludes the endpoint value. To include the endpoint in np.arange()’s output, set the upper limit by +1 that way, it will include your desired value.

range

To create a sequence of numbers, starting from 0 by default, and increments by 1, use the built-in Python range() function.

Syntax

range(start, stop, step)

Example

data = range(6)

for i in data:
   print(i)

Output

0
1
2
3
4
5

In this example, we called the range() function with only one argument that returns a sequence of numbers from 0 to 5. Here too, if you want to include the endpoint then you have to set the upper limit by +1, and that way, it will include your desired endpoint in the output.

np.arange vs range

  1. The main difference between range and np.arange is that the range() function returns an iterator instead of a list and np.arange() function gives a numpy array that consists of evenly spaced values within a given interval.
  2. The range() function generates a sequence of integer values lying between a certain range.
  3. The range() is a built-in function whereas arange() is a numpy library function.
  4. The range() function is more convenient when you need to iterate values using the for loop. The np.arange() function is more useful when you are working with arrays and you need to generate an array based on a specific sequence.

That’s it for np.arange vs range comparison article.

Leave a Comment