Reputation: 23
I would like to increment part of an array in python as fast as possible. I use a simple loop :
>>> test = [0,0,0,0,0]
>>> for i in xrange(1, 3):
test[i] += 1
>>> test
[0,1,1,0,0]
In my program the test list contains several millions elements. Maybe numpy could be the solution ?
Thanks,
Marc
Upvotes: 2
Views: 2623
Reputation: 249133
NumPy is indeed a solution:
import numpy as np
arr = np.array(test)
arr[1:3] += 1
You can use arr.tolist()
if you really need to go back to a list
but better would be to use a NumPy array right from the start, wherever you get your data.
Upvotes: 3