Modifying every alternate element of a sequence

Leo Kislov Leo.Kislov at gmail.com
Tue Nov 28 06:26:04 EST 2006


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.

Use slices:

input[1::2] = [-item for item in input[1::2]]

If you don't want to do it in-place, just make a copy:

wanted = input[:]
wanted[1::2] = [-item for item in wanted[1::2]]

  -- Leo




More information about the Python-list mailing list