What is the numpy.arange() Method

Numpy.arange() method “returns an array with evenly spaced elements as per the interval.” The interval mentioned is half-opened, i.e., [Start, Stop).

Syntax

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

Parameters

The np.arange() function takes four parameters: start, stop, step, and type, and returns evenly spaced values within a given interval.

  1. start: number, optional. Start of an interval. The interval includes this value. The default start value is 0.
  2. stop: number. End of the interval. The interval does not contain a stop value, except when a step is not an integer and a floating-point round-off affects our length. 
  3. step: number, optional. step can’t be zero. Otherwise, you’ll get a ZeroDivisionError. You can’t move away from the start of the increment or decrement is 0.
  4. dtype: The type of an output array. If the dtype is not given, infer the data type from the other input arguments. If dtype is omitted, arange() will try to deduce the array elements from the start, stop, and step types.

Return Value

It returns an array. You can find more details on the parameters and the return value of arange() function in the official documentation.

Example 1: How to Use np.arange() Method

import numpy as np

print(np.arange(4).reshape(2, 2), "\n")

Output

[[0 1]
 [2 3]]

Example 2: Providing all positional range arguments

We can provide all three arguments in the np.arange() function and seek the desired output.

import numpy as np

data = np.arange(start=2, stop=12, step=3)
print(data)

Output

[2 5 8 11]

Example 3: Providing float arguments

The output array values will be float if we provide the float arguments. On the other hand, passing steps in the float will calculate but return the array float values.

import numpy as np

data = np.arange(2, 11.1, 3)
print(data)

Output

[ 2. 5. 8. 11.]

Example 4: Providing Two-Range Arguments

You can omit the step parameter. For example, arange() uses its default value of 1 in the following case. Thus, the next two statements are equivalent.

import numpy as np

data = np.arange(2, 5)
print(data)

Output

[2 3 4]

That’s it.

Related posts

numpy.select()

numpy.argwhere()

numpy.insert()

numpy.append()

numpy.transpose()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.