Modifying every alternate element of a sequence

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Tue Nov 28 13:24:12 CET 2006


On Tue, 28 Nov 2006 02:38:09 -0800, jm.suresh at no.spam.gmail.com wrote:

> I have a list of numbers and I want to build another list with every
> second element multiplied by -1.
> 
> input = [1,2,3,4,5,6]
> wanted = [1,-2,3,-4,5,-6]
> 
> I can implement it like this:
> 
> input = range(3,12)
> wanted = []
> for (i,v) in enumerate(input):
>     if i%2 == 0:
>         wanted.append(v)
>     else:
>         wanted.append(-v)
> 
> But is there any other better way to do this.


Lots of ways.

Other people have given you some solutions. In my opinion, this is
the simplest method of all, if you want to modify input in place:

for i in range(1, len(input), 2):
    input[where] = -input[where]


Here's another method that only works if there are an even number of items:

A = input[0::2] # extended slicing
B = input[1::2]
B = [-x for x in B]
tmp = zip(A, B) # but watch out for odd number of items!
result = []
for t in tmp:
    result.extend(t)


Here's a third method:

factors = [(-1)**i for i in range(len(input))]
output = map(operator.mul, input, factors)


As for which is best, I leave that to you to decide.


-- 
Steven.




More information about the Python-list mailing list