Negative array indicies and slice()

Chris Rebert clp2 at rebertia.com
Mon Oct 29 04:18:32 EDT 2012


On Mon, Oct 29, 2012 at 12:54 AM, Andrew <andrewr3mail at gmail.com> wrote:
> On Sunday, October 28, 2012 9:26:01 PM UTC-7, Ian wrote:
>> On Sun, Oct 28, 2012 at 10:00 PM,  Andrew wrote:
<snip>
> The slice class when passed to __getitem__()  was created to merely pass two numbers and a stride to __getitem__;  As far as I know slice() itself does *nothing* in the actual processing of the elements.  So, it's *redundant* functionality, and far worse, it's restrictive.
>
> The philosophy of Python is to have exactly one way to do something when possible; so, why create a stand alone class that does nothing an existing class could already do, and do it better ?
>
> A simple list of three values would be just as efficient as slice()!
> xrange is more flexible, and can be just as efficient.
>
> So, Have I misunderstood the operation of slice()?  I think I might have... but I don't know.

`slice` is intentionally lenient about the types of the start, stop, and step:
>>> class Foo:
...     def __getitem__(self, slice_):
...         print(slice_)
...         return 42
...
>>> Foo()["a":"b":"c"]
slice('a', 'b', 'c')
42
>>>
Thus, the thing being sliced is free to interpret the parts of the
slice however it wishes; hence, slice() is unable to contain the
"processing" you speak of.
By contrast, xrange() limits itself to integers.
To support the more general case, the slice syntax thus produces a
`slice` rather than an `xrange`.
Doubtlessly, there are also historical issues involved. As implied by
the ugliness of its name, `xrange` was added to the language
relatively later.

Cheers,
Chris



More information about the Python-list mailing list