Last Updated : 02 Dec, 2024
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.
Understanding Negative IndexingIn Python, sequences have both positive and negative indices:
n-1
(where n
is the length of the sequence).-n
for the first element.
# Using negative indexing in a list
a = [10, 20, 30, 40, 50]
# Accessing elements from the end
print(a[-1]) # last element
print(a[-2]) # second last element
Negative Indexing with Strings
Strings in Python are also sequences so we can use negative indexing to access characters from the end of the string.
Python
# String example
s = "Python"
# Accessing characters using negative indexing
print(s[-1]) #(last character)
print(s[-3]) #(third last character)
Let's see some more examples of Negative Indexing
Accessing the Last Few ElementsNegative indexing is especially useful when we need to access elements at the end of a sequence without knowing its length.
Python
a = [5, 10, 15, 20, 25]
# Accessing last two elements
print(a[-2:])
Reversing a Sequence
Negative indexing can be combined with slicing to reverse a sequence.
Python
# Reversing a list
a = [1, 2, 3, 4, 5]
print(a[::-1])
# Reversing a string
s = "Python"
print(s[::-1])
[5, 4, 3, 2, 1] nohtyPNegative Indexing in Nested Structures
Negative indexing also works for nested lists or tuples.
Python
# Nested list
nested_list = [[1, 2], [3, 4], [5, 6]]
# Accessing last sub-list and its last element
print(nested_list[-1])
print(nested_list[-1][-1])
Common Mistakes to Avoid - Index Out of Range
Using a negative index that exceeds the length of the sequence will raise an IndexError
.
a = [1, 2, 3]
print(a[-4]) # Error: IndexError: list index out of range
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4