Re: Modifying every alternate element of a sequence



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)

>>> input = range(3,12)
>>> [i%2==0 and v or -v for (i,v) in enumerate(input)]
[3, -4, 5, -6, 7, -8, 9, -10, 11]

> But is there any other better way to do this.

I'm not sure densely packing it into a list comprehension is necessarily a *better* way, just a more compact way.

To make more sense of it, you might create a helper function that does your comparison work:

def inv_if(v, test):
if test:
return v
else:
return -v

[inv_if(v, i%2==0) for (i,v) in enumerate(input)]


Or you could even do something like

def inv_alternating(t):
i, v = t
if i%2==0:
return v
else:
return -v

[inv_alternating(t) for t in enumerate(input)]

Either compacts it for the actual call within a list comprehension, but it is cleaner to read what's going on.

-tkc





.



Relevant Pages

  • Re: passing class by reference does not work??
    ... instance in my list comprehension in c, then the changes I made to ... sets in INSTANCE variable a the value computed on the RHS. ... You're not "passing the class", ... def getval: return A._val ...
    (comp.lang.python)
  • RE: c[:]()
    ... def b: print 'polly! ... for func in funcs: ... list comprehension or your "perlish" line noise is much more magic to ...
    (comp.lang.python)
  • Re: Newbie question about tuples and list comprehensions
    ... test each RGB band value per pixel, and set it to something else if it ... Why are you trying to do this with a list comprehension? ... Can't wait to try these suggestions out - cheers, idiolect ... def transform_image_getdata: ...
    (comp.lang.python)
  • Re: what is it, that I dont understand about python and lazy evaluation?
    ... I really started to ask myself if python really is lazy, but everything else I wrote in lazy style still worked. ... >> def test: ... As MRAB pointed out, the issue is not with evens, it's with the list comprehension. ...
    (comp.lang.python)
  • Re: Unsupported operand types in if/else list comprehension
    ... it is a string, and keep the item the same if it's anything else: ... I understand that if/else list comprehension should be generally: ... The parentheses around the conditional are unnecessary, but help with readability I think. ... *why* you are doing this in the def of QuoteIfString ...
    (comp.lang.python)