2

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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@MarcMonot: thank you, perhaps you could upvote to offset the beautiful snowflake that downvoted this, and accept it if your problem is resolved by this. Welcome to Stack Overflow.
I already tried by I can't up vote for that I need 15 reputations :)
Ah ok, I marked the answer and earn reputation, then I vote up :) Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.