Skip to content

Negative slicing in Python | Example code

  • by

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']


Negative slicing in Python

Begin slice with 2nd from the end

mystr = "Hello"

Output: lo

End slice 3rd from the end

mystr = "Hello"

Output: He

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

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *