add a number to all odd or even indexed elements in numpy array without loops

Viewed 24967

Lets say your numpy array is:

 A =    [1,1,2,3,4]

You can simply do:

A + .1

to add a number to that every element numpy array

I am looking for a way to add a number to just the odd or even indexed numbers A[::2] +1 while keeping the entire array intact.

Is it possible to add a number to all the odd or even indexed elements without any loops?

4 Answers

If the list didn't start with two 1 and you wanted to add to all even numbers, you could use:

A[1::2] += 0.1

or

A[::-2][::-1] += 0.1

In the latter case, [::-1] is used to reverse the array back to normal order.

Related