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

Jeff Shannon jeff@ccvcorp.com
Thu Jun 12 13:22:01 2003


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

To some degree, yes.

 >>> list1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> list2
['a', 'b', 'c', 'd']
 >>> list1[2:6] = list2[:]
 >>> list1
[0, 1, 'a', 'b', 'c', 'd', 6, 7, 8, 9]
 >>>

You can assign to a list slice.  Note that you can change the length of 
the list by doing so, as well.

 >>> list1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> list1[:2] = list2
 >>> list1
['a', 'b', 'c', 'd', 2, 3, 4, 5, 6, 7, 8, 9]
 >>>

Of course, for this to work, you need to have a list (or other sequence) 
of the new values.

Jeff Shannon
Technician/Programmer
Credit International