user1792403
user1792403

Reputation: 187

Indexing lists in python, for a range of values

To my knowledge, indexing with -1 will bring you up the last item in a list e.g.

list = 'ABCDEFG'
list[-1] 
'G'

But when you are asking for a sequence from the list, -1 gives the second to last term in a list,

list[3:-1] 
'DEF'

Why? I would have expected, and would like to get DEFG

Upvotes: 3

Views: 491

Answers (2)

asthasr
asthasr

Reputation: 9397

It's for the same reason that list[3:4] doesn't include the character at the 4th index; slicing is not inclusive. In addition, you can slice from a character to the end simply by omitting the second slice parameter, as in list[3:].

Upvotes: 1

user2555451
user2555451

Reputation:

It is because the stop (second) argument of slice notation is exclusive, not inclusive. So, [3:-1] is telling Python to get everything from index 3 up to, but not including, index -1.

To get what you want, use [3:]:

>>> list = 'ABCDEFG'
>>> list[3:]
'DEFG'
>>>
>>> list[3:len(list)]  # This is equivalent to doing:  list[3:]
'DEFG'
>>>

Also, just a note for the future: it is considered a bad practice to use list as a variable name. Doing so overshadows the built-in.

Upvotes: 6

Related Questions