[Tutor] Re: Can you modify every nth item in a list with a single assignment?

Andrei project5@redrival.net
Thu Jun 12 21:50:01 2003


> Hm, orignal post required change every nth item of a list, right?
> How about this: I want to multiply every third item with two
> 
>  >>> b = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>  >>> [ item in range(2, len(b), 3) and 2*b[item] or b[item] for item in 
> range(0, len(b))]
> [1, 2, 6, 4, 5, 12, 7, 8, 18]
> 
> range(2) in order to start multiplying at the third item rather than the 
> first.
> 
> This any good?

Obviously this is subject to the and/or trick limitation, which could be 
circumvented like this (we want to add to to all but every third item, 
with item [0] remaining unmodified):

With limitation:
 >>> b = range(9)
 >>> [ item in range(0, len(b), 3) and b[item] or 2+b[item] for item in 
range(0, len(b))]
[2, 3, 4, 3, 6, 7, 6, 9, 10]

Oops, index 0 got modified too (should have been 0, not 2). Let's try again:

 >>> [ (item in range(0, len(b), 3) and [b[item]] or [2+b[item]])[0] for 
item in range(0, len(b))]
[0, 3, 4, 3, 6, 7, 6, 9, 10]

That's better.

Andrei