How To Use Np.Arange(): A Complete Guide For Beginners

Basic Syntax

The np.arange() function is used to create an array with a specified range. Syntax: np.arange([start,] stop[, step]). It generates values from start to stop-1, with an optional step value.

Creating Simple Arrays

For basic usage, use np.arange(5) to create an array [0, 1, 2, 3, 4]. Here, the default start is 0, and the step is 1. The array stops before the stop value.

Specifying Start and Step

You can define custom start and step values. For example, np.arange(2, 10, 2) results in [2, 4, 6, 8], where the sequence starts at 2 and increments by 2.

Floating Point Step

The step value can also be a floating-point number. Example: np.arange(0, 1, 0.1) produces [0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9].

Handling Non-Integer Values

np.arange() works with both integers and floating-point numbers. Ensure the step value is suitable to avoid precision issues when using floating-point numbers.

Efficiency

np.arange() is memory efficient and faster for creating sequences compared to using a for loop or list comprehensions, especially for large ranges.