Modifying every alternate element of a sequence

John Hicken john.hicken at gmail.com
Tue Nov 28 06:21:45 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.
>
> --
> Suresh

I would tend to do this as a list comprehension. In python 2.5 you can
do this:

wanted = [(v if i % 2 == 0 else -v) for (i,v) in enumerate(input)]

(a if b else c) is new to Python 2.5. You don't always need the
brackets, but I think it makes things clearer. See
(http://docs.python.org/whatsnew/pep-308.html) for more details on this
feature.

With earlier versions, you could do

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

That looks less clear to me than your version, though.

John Hicken




More information about the Python-list mailing list