![]() |
VOOZH | about |
Negative indexing in Python allows us to access elements from the end of a sequence like a list, tuple, or string. This feature is unique to Python and makes it easier to work with data structures when we need to retrieve elements starting from the end.
In this article, we will explore negative indexing, how it works and its practical applications.
In Python, sequences have both positive and negative indices:
n-1 (where n is the length of the sequence).-n for the first element.50 40
Strings in Python are also sequences so we can use negative indexing to access characters from the end of the string.
n h
Let's see some more examples of Negative Indexing
Negative indexing is especially useful when we need to access elements at the end of a sequence without knowing its length.
[20, 25]
Negative indexing can be combined with slicing to reverse a sequence.
[5, 4, 3, 2, 1] nohtyP
Negative indexing also works for nested lists or tuples.
[5, 6] 6
Using a negative index that exceeds the length of the sequence will raise an IndexError.