Search code examples
pythonloopslibraries

Is it possible to increment the value of a range of array elements by a constant without looping through the list?


Are there any modules or libraries in python that could help me with this? I mean to do this with a complexity of O(1).


Solution

  • You can use numpy to do this

    >>> import numpy as np
    >>> data = np.arange(10)
    >>> data
    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    >>> data[2:6] += 5
    >>> data
    array([ 0,  1,  7,  8,  9, 10,  6,  7,  8,  9])