KGS
KGS

Reputation: 297

Python Tuple Slicing

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

Upvotes: 3

Views: 29814

Answers (4)

aady
aady

Reputation: 45

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.

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304137

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

Upvotes: 10

twj
twj

Reputation: 767

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

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

yields

5

Upvotes: 14

Christian Tapia
Christian Tapia

Reputation: 34146

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.

Upvotes: 5

Related Questions