Performing bulk arithmetic operations on python list

Viewed 941

I have a list of integers and I want to perform operations like addition, multiplication, floor division on every element of list slice (sub array) or at certain indexes (eg. range(start, end, jump) ) efficiently. The number being added or multiplied by each element of list slice is constant (say 'k').

For example:

    nums = [23, 44, 65, 78, 87, 11, 33, 44, 3]
    for i in range(2, 7, 2):
        nums[i] //= 2 # here 2 is the constant 'k'
    print(nums)
    >>>    [23, 44, 32, 78, 43, 11, 16, 44, 3]

I have to perform these operations several times on different slices/ranges and the constant 'k' varies for different slices/ranges. The obvious way to do this is to run a for loop and modify the value of elements, but that isn't fast enough. You can do this efficiently by using a numpy array because it supports bulk assignment/modification but I am looking for a way to do this in pure python.

1 Answers
Related