Specify start and length, beside start and end, in slices

Peter Abel PeterAbel at gmx.net
Mon May 24 16:43:36 EDT 2004


Noam Raphael <noamr at correctme.users.sourcephorge.net> wrote in message news:<c8l3s3$27o$1 at news.iucc.ac.il>...
> Hello,
> Many times I find myself asking for a slice of a specific length, and 
> writing something like l[12345:12345+10].
> This happens both in interactive use and when writing Python programs, 
> where I have to write an expression twice (or use a temporary variable).
> 
> Wouldn't it be nice if the Python grammar had supported this frequent 
> use? My idea is that the expression above might be expressed as 
> l[12345:>10].
> 
> This change, as far as I can see, is quite small: it affects only the 
> grammar and byte-compiling, and has no side effects.
> 
> The only change in syntax is that short_slice would be changed from
> [lower_bound] ":" [upper_bound]
> to
> ([lower_bound] ":" [upper_bound]) | ([lower_bound] ":>" [slice_length])
> 
> Just to show what will happen to the byte code: l[12345:12345+10] is 
> compiled to:
> LOAD_GLOBAL              0 (l)
> LOAD_CONST               1 (12345)
> LOAD_CONST               1 (12345)
> LOAD_CONST               2 (10)
> BINARY_ADD
> SLICE+3
> 
> I suggest that l[12345:>10] would be compiled to:
> LOAD_GLOBAL              0 (l)
> LOAD_CONST               1 (12345)
> DUP_TOP
> LOAD_CONST               2 (10)
> BINARY_ADD
> SLICE+3
> 
> Well, what do you think? I would like to hear your comments.
> 
> Have a good day (or night),
> Noam Raphael

Python has ready a workaround for nearly ervery problem.
What about the following?

>>> # iNCREMENTALslICE
>>> isl=lambda l,start,increment:l.__getslice__(start,start+increment)
>>> l='zero one two three four five six'.split()
>>> l
['zero', 'one', 'two', 'three', 'four', 'five', 'six']
>>> isl(l,3,3)
['three', 'four', 'five']
>>> 

Regards
Peter



More information about the Python-list mailing list