1

If I have x = (0, 1, 2, 3, 4), and I want to get all the elements other the first two, but in reverse order, why is it supposed to be x[:1:-1] or x[:-4:-1] rather than x[2::-1]?

shaoyl85
  • 1,854
  • 18
  • 30
  • 1
    http://stackoverflow.com/questions/509211/explain-pythons-slice-notation/509295#509295 – astrosyam Jan 08 '16 at 01:39
  • 1
    The specific question asked here is not covered by the referenced answer. The issue is that when the stride (the third item in the slicing notation) is negative the function of the first and second indices is reversed. – holdenweb Jan 08 '16 at 02:40

1 Answers1

0

The syntax is arr[start:stop:step].

x[2::-1] would start from index 2 until the end of the array, so [x[2], x[1], x[0]], which is not what you want.

If the step is negative, then the start defaults to -1. In python, arr[-1] would be the last element of the array, arr[-2] would be the second last etc. So x[:1:-1] == x[:-4:-1] (since 1 == -4 (mod 5)) which is [x[-1], x[-2], x[-3]] == x[4], x[3], x[2].

M. Shaw
  • 1,742
  • 11
  • 15