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

Terry Reedy tjreedy at udel.edu
Fri May 21 15:08:10 EDT 2004


"Noam Raphael" <noamr at correctme.users.sourcephorge.net> wrote in message
news:c8l3s3$27o$1 at news.iucc.ac.il...

> 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).

With an expression, I'd go for the temp var.

> Wouldn't it be nice if the Python grammar had supported this frequent
> use?

I take this as 'directly support' versus the current indirect support via
start+len.
My answer: superficially (in isolation) yes, but overall, in the context of
Python's somewhat minimalistic grammar/syntax, no.  Two ways to slice might
easily be seen as one too many.  In addition, the rationale for this, your
favorite little addition, would admit perhaps 50 others like it.

> My idea is that the expression above might be expressed as l[12345:>10].

Sorry, this strike me as ugly, too much like and easily confused with
l[12345:-10], and too much looking like a syntax error.

Given that some other languages slice with (start,len) arguments (but not
then, that I remember or know of, also with a start,stop option), I am
*sure* that Guido thought carefully about the issue.  A plus with his
choice is ability to offset (index) from the end *without* calling the len
function.

> This change, as far as I can see, is quite small: it affects only the
> grammar and byte-compiling, and has no side effects.

Except the cognitive dissonance of two *almost* identical syntaxes and the
flood of other 'small', 'no side effect' change requests.

> Well, what do you think? I would like to hear your comments.

Your wish ...

Terry J. Reedy







More information about the Python-list mailing list