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

Noam Raphael noamr at correctme.users.sourcephorge.net
Fri May 21 10:31:30 EDT 2004


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



More information about the Python-list mailing list