Negative array indicies and slice()

Ian Kelly ian.g.kelly at gmail.com
Mon Oct 29 13:27:47 EDT 2012


On Mon, Oct 29, 2012 at 1:54 AM, Andrew <andrewr3mail at gmail.com> wrote:
> My intended inferences about the iterator vs. slice question was perhaps not obvious to you; Notice: an iterator is not *allowed* in __getitem__().

Yes, I misconstrued your question.  I thought you wanted to change the
behavior of slicing to wrap around the end when start > stop instead
of returning an empty sequence.  What you actually want is a new
sequence built from indexes supplied by an iterable.  Chris has
already given you a list comprehension solution to solve that.  You
could also use map for this:

new_seq = list(map(old_seq.__getitem__, iterable))

Since you seem to be concerned about performance, I'm not sure in this
case whether the map or the list comprehension will be faster.  I'll
leave you to test that on your intended hardware.

> 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.

I'm aware of what is possible in C with pointer arithmetic.  This is
Python, though, and Python by design has neither pointers nor pointer
arithmetic.  In any case, initializing the pointer to the end of the
array would still not do what you want, since the positive indices
would then extend past the end of the array.



More information about the Python-list mailing list