3

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

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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:].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.