Negative array indicies and slice()
Andrew
andrewr3mail at gmail.com
Mon Oct 29 03:54:29 EDT 2012
On Sunday, October 28, 2012 9:26:01 PM UTC-7, Ian wrote:
> On Sun, Oct 28, 2012 at 10:00 PM, Andrew wrote:
>
> > Hi Ian,
>
> > Well, no it really isn't equivalent.
>
> > Consider a programmer who writes:
>
> > xrange(-4,3) *wants* [-4,-3,-2,-1,0,1,2]
>
> >
>
> > That is the "idea" of a range; for what reason would anyone *EVER* want -4 to +3 to be 6:3???
>
>
>
> That is what ranges do, but your question was about slices, not ranges.
Actually, I said in the OP:
"I also don't understand why slice() is not equivalent to an iterator, but can replace an integer in __getitem__() whereas xrange() can't."
=========================
Thank you for the code snippet; I don't think it likely that existing programs depend on nor use a negative index and a positive index expecting to take a small chunk in the center... hence, I would return the whole array; Or if someone said [-len(listX) : len(listX)+1 ] I would return the whole array twice.
That's the maximum that is possible.
If someone could show me a normal/reasonable script which *would* expect the other behavior, I'd like to know; compatibility is important.
=========================
My intended inferences about the iterator vs. slice question was perhaps not obvious to you; Notice: an iterator is not *allowed* in __getitem__().
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.
In 'C', where Python is written, circularly linked lists -- and arrays are both very efficient ways of accessing data. Arrays can, in fact, have negative indexes -- perhaps contrary to what you thought. One merely defines a variable to act as the base pointer to the array and initialize it to the *end* of the array. Nor is the size of the data elements an issue, since in Python all classes are accessed by pointers which are of uniform size. I routinely do this in C.
Consider, also, that xrange() does not actually create a list -- but merely an iterator generating integers which is exactly what __getitem__ works on.
So, xrange() does not need to incur a memory or noticeable time penalty.
>From micro-python, it's clear that their implementation of xrange() is at the 'C' level; which is extremely fast.
More information about the Python-list
mailing list