Using a negative number as an index in the slice method is called Negative slicing in Python. It returns the nth element from the right-hand side of the list (as opposed to the usual left-hand side).
Python supports using negative numbers to index into a string: -1 means the last char, -2 is the next to last, and so on.
Examples of Negative slicing in python
Simple example code.
Get Last value using the negative index value
s[0:-1] is exactly the same as calling
myList = ['A', 'B', 'C', 'D', 'E'] print(myList[-1])
Begin slice with 2nd from the end
mystr = "Hello" print(mystr[-2:])
End slice 3rd from the end
mystr = "Hello" print(mystr[:-3])
Do comment if you have any doubts and suggestions on this Python slice topic.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.