[Python-ideas] More useful slices

Steven D'Aprano steve at pearwood.info
Mon Feb 2 02:36:49 CET 2015


On Sun, Feb 01, 2015 at 10:18:33PM +0100, Todd wrote:
> On Feb 1, 2015 6:27 PM, "Steven D'Aprano" <steve at pearwood.info> wrote:

> > In other words, the similarity between slices and ranges is not as close
> > as you think.
> 
> Fair enough.  But it doesn't really affect my proposal.  It would just be
> that this syntax only allows a subset of what you can do with slices.

It undercuts the justification for the proposal. Greg has also shown 
that even with purely integer values, slices and ranges behave differently.

Slice objects are not a special case of ranges, and ranges are not a 
special case of slice objects. They behave differently, have different 
restrictions on their parameters, and different purposes. As far as I 
can see, virtually the only similarity is the names of the three 
parameters: start, stop, step.

You might object that there is an important similarity that I've missed: 
slices (well, some slices) provide the same integer indexes as range 
does. That is, for at least *some* combinations of integers a, b and c, 
we have this invariant:

seq[a:b:c] == [seq[i] for i in range(a, b, c)]

But that's not a property of the slice object, that's a property of the 
sequence! Slice object merely record the start, stop, step, which can be 
arbitrary values in arbitrary order, and the sequence decides how to 
interpret it.

The docs carefully don't describe the meaning of a slice object except 
as a bundle of start, stop, step attributes:

https://docs.python.org/3/library/functions.html#slice

That's because slice objects don't have any meaning except that which 
the sequence chooses to give it. That is not true for range objects.

(By the way, the docs are wrong when they say slice objects have no 
other explicit functionality: they also have an indices method.)

The above invariant is the conventional meaning, of course, and I'm not 
suggesting that there are a lot of classes that ignore that conventional 
meaning and do something else. But slice objects exist to be a simple 
bundle of three attributes with arbitrary values, and ranges exist to be 
a linear iterable of integers. The fact that sometimes they appear to 
kind of almost overlap in meaning is incidental.


-- 
Steven


More information about the Python-ideas mailing list