np.arange() | NumPy Arange Function in Python

Posted in /  

np.arange() | NumPy Arange Function in Python
vinaykhatri

Vinay Khatri
Last updated on December 23, 2024

    The Python NumPy library comes with many inbuilt functions and arange() is one of those. The Python numpy arange() function is similar to the Python range() function. As the Python range() function return a range() iterable object of elements similarly the numpy arange() function returns a numpy ndarray object containing elements with evenly spaced intervals.

    Let's say you want to create a numpy array of 100 elements values from o to 99, so instead of writing all the values in a list and converting it to a numpy array or using a for a loop. We can simply use the Python NumPy arange() function and create an array of 100 elements with a single statement.

    What is numpy.arrange() Function?

    NumPy arrage() Syntax

    np.arange(start, stop, step, dtype=none)

    Parameters

    • start, represent the starting number from where the element values of the array should start.
    • end represents the excluded ending point up to which the arrange function should put numbers.
    • step represents the gap or interval between the elements, by default its value is 1.
    • dtype represent the data type of all the elements.

    How to use numpy.arange() function?

    While using the arange() function all the other parameters are optional except the end .

    Example 1: np.arange() function with end parameter

    >>> import numpy as np
    >>> arr = np.arange(9)
    >>> print(arr)
    [0 1 2 3 4 5 6 7 8]

    The end parameter value does not include in the array.

    Example 2: np.arange() function with start and end parameter

    >>> import numpy as np
    >>> arr = np.arange(1, 20)
    >>> print(arr)
    [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
    start =1 (include), and end = 20 (excluded)

    Example 3: np.arange() function with start, end, and step parameter

    >>> import numpy as np
    >>> arr = np.arange(1, 20, 2)
    >>> print(arr)
    [ 1 3 5 7 9 11 13 15 17 19]

    Example 4: np.arange() function with start, end, step and type parameter

    >>> import numpy as np
    >>> arr = np.arange(1, 20, 2, float)
    >>> print(arr)
    [ 1. 3. 5. 7. 9. 11. 13. 15. 17. 19.]

    Summary

    • The Python numpy arange() function is used to create a numpy array of elements with equally spaced intervals.
    • It can accept 4 parameters start, end, steps, and type.
    • Only end parameter is mandatory and the other 3 are optional.
    • The arange() function includes the start value but excludes the end value for the array.

    People are also reading:

    Leave a Comment on this Post

    0 Comments