Re: Modifying every alternate element of a sequence



Wow, I was in fact searching for this syntax in the python tutorial. It
is missing there.
Is there a reference page which documents all possible list
comprehensions.
--
Suresh
Leo Kislov wrote:
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.

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

.



Relevant Pages

  • Re: multiline matching
    ... I read over the reference, but I guess I am missing the ... syntax as I cannot get it to work properly. ... Jose Malacara ...
    (perl.beginners)
  • RE: FileDateTime function error
    ... VBA reference problem or your syntax is incorrect. ... Dave Hargis, Microsoft Access MVP ... I don't see anything marked "missing" in my ...
    (microsoft.public.access.externaldata)
  • FileDateTime function error
    ... I found the syntax below from a 2006 post but I'm getting an Undefined ... Function error when I try to use it in Access 2007. ... reference I'm missing? ... I don't see anything marked "missing" in my ...
    (microsoft.public.access.externaldata)
  • Re: RtlStringCbVPrintfA problem
    ... I am using WinXP DDK 2600.1106 build. ... : missing '{' before '__stdcall' ... Compiling - xxxd_main.c for i386 ...
    (microsoft.public.development.device.drivers)
  • Re: RtlStringCbVPrintfA problem
    ... I am using WinXP DDK 2600.1106 build. ... : missing '{' before '__stdcall' ... Compiling - xxxd_main.c for i386 ...
    (microsoft.public.development.device.drivers)