Negative array indicies and slice()

MRAB python at mrabarnett.plus.com
Sun Oct 28 23:45:58 EDT 2012


On 2012-10-29 03:12, 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 [].
> }}}
>
If the stride is positive (if omitted it defaults to 1), the slice is
from the start index to one before the end index, and a negative index
counts from the end.

a[-4:3] is equivalent to a[len(a)-4:3], which is an empty list if
len(a)-4 >= 3.

It doesn't wrap around.




More information about the Python-list mailing list