0
0
NumpyHow-ToBeginner ยท 3 min read

How to Use np.arange in NumPy for Creating Arrays

Use np.arange(start, stop, step) to create a NumPy array with values starting from start up to but not including stop, incremented by step. If start is omitted, it defaults to 0, and if step is omitted, it defaults to 1.
๐Ÿ“

Syntax

The basic syntax of np.arange is:

  • start: The first value in the array (inclusive). Defaults to 0 if not provided.
  • stop: The end value (exclusive), the array will include values up to but not including this.
  • step: The difference between consecutive values. Defaults to 1.
python
np.arange(stop, start=0, step=1)
๐Ÿ’ป

Example

This example creates an array starting at 2, ending before 10, with steps of 2.

python
import numpy as np

arr = np.arange(2, 10, 2)
print(arr)
Output
[2 4 6 8]
โš ๏ธ

Common Pitfalls

One common mistake is misunderstanding that the stop value is not included in the output array. Another is using a step of zero, which causes an error. Also, using floating point step can lead to precision issues.

python
import numpy as np

# Wrong: step=0 causes error
# arr = np.arange(0, 5, 0)  # ValueError

# Right: step must be non-zero
arr = np.arange(0, 5, 1)
print(arr)

# Floating point step example
arr_float = np.arange(0, 1, 0.2)
print(arr_float)
Output
[0 1 2 3 4] [0. 0.2 0.4 0.6 0.8]
๐Ÿ“Š

Quick Reference

ParameterDescriptionDefault
startStart of interval (inclusive)0
stopEnd of interval (exclusive)Required
stepSpacing between values1
โœ…

Key Takeaways

np.arange creates arrays with evenly spaced values from start to stop (exclusive).
If start is omitted, it defaults to 0; step defaults to 1 if omitted.
The stop value is not included in the output array.
Step cannot be zero and floating point steps may have precision issues.
Use np.arange for simple ranges; for precise decimal steps, consider np.linspace.