Re: Modifying every alternate element of a sequence




jm.suresh@xxxxxxxxxxxxxxxxx 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

.



Relevant Pages

  • Re: OT: Why is C so popular?
    ... >> But see my last paragraph in my previous post. ... Those brackets which make ... I look at Python code and I get lost. ... I want the braces, ...
    (Debian-User)
  • Re: why brackets & commas in func calls cant be ommited? (maybe it couldbe PEP?)
    ... Mathematicians sometimes use brackets to indicate function application and ... I mention 'attempted' because in Python there is no ... The math notations without brackets ... generally don't have to deal with callables returning callables. ...
    (comp.lang.python)
  • Re: Why Python does *SLICING* the way it does??
    ... In the context of current python lists yes. ... But outsides the brackets the scope where this ...
    (comp.lang.python)
  • Re: Why the expression "(1)" is not an one-arity tuple, but int ?
    ... But when I call my library function with a 1-arity tuple (for example ... How could I tell Python that "" is not an integer, ... Tuples in Python are recognized/defined not by the brackets, ... the brackets just function to specify the exact beginning ...
    (comp.lang.python)
  • Re: Is there a better way of doing this?
    ... > lengthy than python code i have read..... ... > while(newNS): ... See above comment about whitespace inside brackets. ... drop the brackets from the elif statement and the semi-colons. ...
    (comp.lang.python)