Modifying every alternate element of a sequence

Antoon Pardon apardon at forel.vub.ac.be
Tue Nov 28 12:36:55 CET 2006


On 2006-11-28, jm.suresh at no.spam.gmail.com <jm.suresh at 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.

Wether this is better, I'll leave that for others to decide. But this
is a possibility:

wanted = [ (1 - 2*(i%2)) * item for i, item in enumerate(input)]

-- 
Antoon Pardon



More information about the Python-list mailing list