3

Given that -1 goes back to the first term in a tuple, and the end index of a slice stops before that index, why does

x=(1,2,3,4,5)
x[0:-1]

yield

(1, 2, 3, 4)

instead of stopping at the index before the first which is 5?

Thanks

KGS
  • 277
  • 2
  • 4
  • 11
  • 1
    [This question has been answered before and very thoroughly.](http://stackoverflow.com/questions/509211/pythons-slice-notation) –  Jan 15 '14 at 04:41

4 Answers4

14

-1 does not go back to the first term in a tuple

x=(1,2,3,4,5)
x[-1]

yields

5
twj
  • 759
  • 5
  • 12
10

It helps to think of the slicing points as between the elements

x = (   1,   2,   3,   4,   5   )
      |    |    |    |    |    |
      0    1    2    3    4    5
     -5   -4   -3   -2   -1
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
5

Slicing works like this:

x[start : end : step]

In your example, start = 0, so it will start from the beginning, end = -1 it means that the end will be the last element of the tuple (not the first). You are not specifying step so it will its default value 1.

This link from Python docs may be helpful, there are some examples of slicing.

Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
0

A -ve value in any python sequences means :

Val = len(sequence)+(-ve value)

Either start/stop from/to len(sequence)+(-ve value), depending on what we specify.

ketan
  • 19,129
  • 42
  • 60
  • 98
aady
  • 35
  • 2