Possible improvement to slice opperations.

Patrick Maupin pmaupin at gmail.com
Mon Sep 5 23:53:55 EDT 2005


I previously wrote (in response to a query from Ron Adam):

> In any case, you asked for a rationale.  I'll give you mine:
>
> >>> L = range(10)
> >>> L[3:len(L):-1] == [L[i] for i in range(3,len(L),-1)]
> True
> >>>

After eating supper, I just realized that I could probably make my
point a bit clearer with a slightly longer example:

>>> L = range(10)
>>> for stride in [-3, -2, -1, 1, 2, 3]:
...     for start in range(len(L)):
...         for end in range(len(L)):
...             P = L[start:end:stride]
...             Q = [L[i] for i in range(start, end, stride)]
...             assert P == Q

This should never fail with an assertion error.  You will note that it
shows that, for non-negative start and end values, slicing behavior is
_exactly_ like extended range behavior.  I cannot imagine that the
behavior of range() could be made any more intuitive than it already
is.  I personally feel that your proposed change makes slice() less
intuitive on its own, but even if I did not feel that way, your way
would have to be SIGNIFICANTLY better than the current way to make it
worthwhile to make slice() behavior differ from that of range().

In my initial skimming of your post, I originally thought you were
referring to negative start and end values.  Negative start and end
values will sometimes cause issues, but the utility of their current
implementation far outweighs the few corner cases which (as I mentioned
in an earlier post) sometimes need some special case logic to deal
with.

Regards,
Pat




More information about the Python-list mailing list