0
0
NumPydata~5 mins

np.arange() for range arrays in NumPy

Choose your learning style9 modes available
Introduction

We use np.arange() to create arrays with numbers in a sequence. It helps us quickly make lists of numbers for calculations or analysis.

When you need a list of numbers from 0 to 9 to count or loop over.
When you want to create time steps like every 0.5 seconds from 0 to 5 seconds.
When you want to generate indexes for data points in a dataset.
When you want to create a range of values to plot a graph.
When you want to test a function with a sequence of inputs.
Syntax
NumPy
import numpy as np

array = np.arange(start, stop, step)

start is where the sequence begins (default is 0).

stop is where the sequence ends but is not included.

step is how much to increase each time (default is 1).

Examples
Creates numbers from 0 up to 4 (5 is not included).
NumPy
import numpy as np

array = np.arange(5)
print(array)
Creates numbers from 2 up to 6.
NumPy
import numpy as np

array = np.arange(2, 7)
print(array)
Creates numbers from 1 to 9, stepping by 2 each time.
NumPy
import numpy as np

array = np.arange(1, 10, 2)
print(array)
Creates numbers from 10 down to 6, stepping down by 1.
NumPy
import numpy as np

array = np.arange(10, 5, -1)
print(array)
Sample Program

This program shows how to create arrays with np.arange() using different starts, stops, and steps. It also shows what happens if start and stop are the same.

NumPy
import numpy as np

# Create an array from 0 to 9
array_start_0 = np.arange(10)
print('Array from 0 to 9:', array_start_0)

# Create an array from 5 to 14
array_start_5 = np.arange(5, 15)
print('Array from 5 to 14:', array_start_5)

# Create an array from 0 to 5 with step 0.5
array_step_half = np.arange(0, 5, 0.5)
print('Array from 0 to 5 with step 0.5:', array_step_half)

# Create an empty array when start equals stop
array_empty = np.arange(3, 3)
print('Empty array when start equals stop:', array_empty)
OutputSuccess
Important Notes

Time complexity: Creating an array with np.arange() is fast and runs in O(n), where n is the number of elements.

Space complexity: The array uses memory proportional to the number of elements created.

A common mistake is forgetting that the stop value is not included in the array.

Use np.arange() when you want a sequence of numbers with a fixed step. For floating point steps, sometimes np.linspace() is better to avoid rounding issues.

Summary

np.arange() creates arrays with numbers in a range you choose.

The stop value is not included in the array.

You can set the start, stop, and step to control the sequence.