Negative array indicies and slice()

Ian Kelly ian.g.kelly at gmail.com
Sun Oct 28 23:42:50 EDT 2012


On Sun, Oct 28, 2012 at 9:12 PM,  <andrewr3mail at gmail.com> wrote:
> The slice operator does not give any way (I can find!) to take slices from negative to positive indexes, although the range is not empty, nor the expected indexes out of range that I am supplying.
>
> Many programs that I write would require introducing variables and logical statements to correct the problem which is very lengthy and error prone unless there is a simple work around.
>
> I *hate* replicating code every time I need to do this!
>
> I also don't understand why slice() is not equivalent to an iterator, but can replace an integer in __getitem__() whereas xrange() can't.
>
>
> Here's an example for Linux shell, otherwise remove /bin/env...
> {{{#!/bin/env python
> a=[1,2,3,4,5,6,7,8,9,10]
> print a[-4:3]  # I am interested in getting [7,8,9,10,1,2] but I get [].
> }}}


For a sequence of length 10, "a[-4:3]" is equivalent to "a[6:3]",
which is an empty slice since index 6 is after index 3.

If you want it to wrap around, then take two slices and concatenate
them with "a[-4:] + a[:3]".



More information about the Python-list mailing list