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

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu Jun 12 16:14:02 2003


On Wed, 11 Jun 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?


Hi Alan,


We almost have this at the moment; Python 2.2 supports a limited form of
this for whole consecutive slices:

###
>>> l = range(20)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> l[:5] = [1, 1, 1, 1, 1, 1]
>>> l
[1, 1, 1, 1, 1, 1, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
###

and in the upcoming Python 2.3, it should be easy to express this with the
extended slicing syntax:

    http://www.python.org/doc/2.3b1/whatsnew/section-slices.html


Lots of good stuff to look forward to.  *grin*

(I think Numeric Python also supports something like this in its matrix
class; does someone have comments about it?)



But until Python 2.3 becomes mainstream, we may need to stick with the
loop approach.



Good luck!