Negative slicing in Python | Example code

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

Calling s[0:-1] is exactly the same as calling s[:-1].

myList = ['A', 'B', 'C', 'D', 'E']
print(myList[-1])

Output:

Negative slicing in Python

Begin slice with 2nd from the end

mystr = "Hello"
print(mystr[-2:])

Output: lo

End slice 3rd from the end

mystr = "Hello"
print(mystr[:-3])

Output: He

Do comment if you have any doubts and suggestions on this Python slice topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.