We earn commission when you buy through affiliate links.

This does not influence our reviews or recommendations.Learn more.

Negative index starts from-1to-(iterable_length).

We will use the negative slicing to get the elements from the end of an iterable.

Lets see an example.

The above program will print the last and first characters from the string using negative indexing.

How do we remove the last element from the string usingslicing?

Its just a line of code.

We know how to extract a part of the string using slicing.

Lets apply the same thing with a negative index to remove the last character from the string.

Lets focus on the second line in the above code.

Thats the magic line in the code.

You will getGeekflareas output if you launch the above code.

So, we can use it to remove the last element of the string.

We dont have to write more than a line of code to remove the last char from the string.

Lets see the code snippet.

We have given the last character of the string to thestripmethod.

It removes the last character from the string and returns a copy without the last character.

It will printGeekflarein the console, if you execute it.

Lets say we have a file that contains multiple lines of text.

And we need to remove the last word from each line in the file.

The file contains the following data.

See the code below.

Hope you enjoyed the tutorial.