Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the python slice syntax wrap around from negative to positive indices?

Tags:

python

slice

I noticed, given l = [1,2,3], that l[-1:] returns [3] as expected, but that l[-1:0] returns [], very much unlike what I expected. I then tried [-1:1], which I expected to return [3,1], but it also returns [].

Is there a good reason why the slice syntax does not wrap around from negative to positive indices (and the other way round)?

It seems it would be pretty useful and pretty straightforward to implement, but maybe I'm missing something.

like image 664
rkrzr Avatar asked Sep 30 '14 10:09

rkrzr


1 Answers

Slicing has a very simple definition: you go from start by jumps of step as long as you are below stop. If start or step are negative, first add the length of the array.

One time your suggestion causes irksome behaviour is:

x[10:-10]

If x[-10] is after x[10], you want the slice from x[10] to x[len(x)-10-1]. If you have wrap-around, you'll have the slice x[10:] + x[:-10], which is mostly useless.

Wrap-around behaviour is easy to emulate (eg x[m:] + x[:n]) with the current behaviour, but the current, more useful, behavior is hard to emulate with wrap-around.

like image 134
Veedrac Avatar answered Sep 30 '22 15:09

Veedrac