Negative Indexing in Python

Negative Indexing for Strings

You can index single characters in strings using the bracket notation. The first character has index 0, the second index 1, and so on. Did you ever want to access the last element in the string? Counting the indices can be a real pain for long strings with more than 8-10 characters.

But no worries, Python has a language feature for this: negative indexing.

Positive Index: The first character has index 0, the second character has index 1, and the i-th character has index i-1.

Negative Index: The last character has index -1, the second last character has index -2, and the i-th last character has index -i.

Instead of start counting from the left, you can also start from the right. Access the last character with the negative index -1, the second last with the index -2, and so on.

x = 'cool'
print(x[-1] + x[-2] + x[-4] + x[-3])
# loco

Negative Indexing for Lists

Suppose, you have list ['u', 'n', 'i', 'v', 'e', 'r', 's', 'e']. The indices are simply the positions of the characters in the list.

(Positive) Index01234567
Elementβ€˜uβ€™β€˜nβ€™β€˜iβ€™β€˜vβ€™β€˜eβ€™β€˜rβ€™β€˜sβ€™β€˜e’
Negative Index-8-7-6-5-4-3-2-1

You can learn more about how to access the last and last n characters of a list or a string in our detailed article.

Related Article: How to Get the Last Element of a Python List?

In summary, there are two ways to index sequence positions, from the left and from the right with positive or negative indices.

Related Code Puzzle

Can you solve this code puzzle in our interactive puzzle app?

Negative Indexing Puzzle

Are you a master coder?
Test your skills now!

Leave a Comment

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