[Python-Dev] Negative slice steps considered unhealthy (extended slicing for lists)
Guido van Rossum
guido@beopen.com
Mon, 31 Jul 2000 23:01:34 -0500
> I think there are some big conceptual problems with allowing
> negative steps in a slice.
>
> With ordinary slices, everything is very clear if you think
> of the indices as labelling the points between the list
> elements.
>
> With a step, this doesn't work any more, and you have to
> think in terms of including the lower index but excluding the
> upper index.
>
> But what do "upper" and "lower" mean when the step is negative?
> There are several things that a[i:j:-1] could plausibly mean:
>
> [a[i], a[i-1], ..., a[j+1]]
>
> [a[i-1], a[i-2], ..., a[j]]
>
> [a[j], a[j-1], ..., a[i+1]]
>
> [a[j-1], a[j-2], ..., a[i]]
>
> And when you consider negative starting and stopping values,
> it just gets worse. These have no special meaning to range(),
> but in list indexing they do. So what do they mean in a slice
> with a step? Whatever is chosen, it can't be consistent with
> both.
>
> In the face of such confusion, the only Pythonic thing would
> seem to be to disallow these things.
You have a point! I just realized today that my example L[9:-1:-1]
does *not* access L[0:10] backwards, because of the way the first -1
is interpreted as one before the end of the list L. :(
But I'm not sure we can forbid this behavior (in general) because the
NumPy folks are already using this. Since these semantics are up to
the object, and no built-in objects support extended slices (yet), I'm
not sure that this behavior has been documented anywhere except in
NumPy.
However, for built-in lists I think it's okay to forbid a negative
step until we've resolved this...
This is something to consider for patch 100998 which currently
implements (experimental) extended slices for lists...
--Guido van Rossum (home page: http://www.pythonlabs.com/~guido/)