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

R. Alan Monroe R. Alan Monroe" <amonroe@columbus.rr.com
Thu Jun 12 23:21:01 2003


> At 10:20 PM 6/11/2003 -0400, R. Alan Monroe wrote:

>>I know I can modify every nth list item using a for loop over a
>>range(start,end,n), but can it be done in a single assignment, without
>>a loop?

> No. Any operation on multiple elements of a list in any language is going 
> to be implemented as a loop at some level, with the exception of 
> vector-processing hardware such as the Cray computers.

> What is your goal here?

I'd like to, for instance, draw a column of pixels in a 2d video
buffer that's implemented as a 1d array.

> If you want Python code without using a for or while statement consider:

>  >>> def foo((a,b)):
> ...   if b%2:return a
> ...   else:return a+5
>  >>> l = [1, 2, 3, 4]
>  >>> map(foo,zip(l,range(len(l))))
> [1, 7, 3, 9]


Cool. "Lonetwin" also emailed me offlist, and steered me toward
figuring out this method.


>>> a=[1,2,3,4,5,6,7,8,9,10]

>>> def f(x):
...     a[x]=0

>>> [f(x) for x in range(0,10,2)]

>>> a
[0, 2, 0, 4, 0, 6, 0, 8, 0, 10]


Alan