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

Alfred Milgrom fredm@smartypantsco.com
Thu Jun 12 21:37:03 2003


In answer to Alan Monroe's initial question:

 > 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?

It's possible to do it using list comprehension (but rather pointless) as 
follows:

 >>> list1 = [1,2,3,4,5,6,7,8,9]
 >>> n = 3
 >>> list2 = [list1[i]*(i%n!=n-1) or 'new item' for i in range(len(list1))]
 >>> list2
[1, 2, 'new item', 4, 5, 'new item', 7, 8, 'new item']

'new item' can of course be a manipulation of list1 items or come from 
another list, etc.

Fred Milgrom