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

Larry Bates lbates at swamisoft.com
Fri May 21 19:11:13 EDT 2004


I think it is odd that I have never encounter
many of these types of constructs repeatedly in
my code.  Perhaps you could share a little more
of where you see this type of think popping up
a lot?  I suspect that there is another method
for solving the problem that might be faster
and easier to read/program.

Larry Bates,
Syscon, Inc.


"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





More information about the Python-list mailing list