Modifying every alternate element of a sequence

Roberto Bonvallet Roberto.Bonvallet at cern.ch
Tue Nov 28 07:14:31 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.
[...]
> But is there any other better way to do this.

I think the best way is the one that uses slices, as somebody suggested
in this thread.  This is another (worse) way, just for fun:

    >>> from itertools import cycle
    >>> input = [1, 2, 3, 4, 5, 6]
    >>> wanted = [x * sign for x, sign in zip(input, cycle([1, -1]))]
    >>> wanted
    [1, -2, 3, -4, 5, -6]

Cheers,
-- 
Roberto Bonvallet



More information about the Python-list mailing list