What is Negative Indexing in Python?
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 Indexing
In Python, sequences have both positive and negative indices:
- Positive Indexing: Starts from 0 and goes up to
n-1
(where n
is the length of the sequence). - Negative Indexing: Starts from -1 for the last element and goes up to
-n
for the first element.
Python
# 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 Elements
Negative 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])
Output[5, 4, 3, 2, 1]
nohtyP
Negative 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
.
Python
a = [1, 2, 3]
print(a[-4]) # Error: IndexError: list index out of range
Similar Reads
numpy.negative() in Python numpy.negative() function is used when we want to compute the negative of array elements. It returns element-wise negative value of an array or negative value of a scalar. Syntax : numpy.negative(arr, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, ext
2 min read
numpy.index() in Python numpy.core.defchararray.index(arr, substring, start=0, end=None): Finds the lowest index of the sub-string in the specified range But if substring is not found, it raises ValueError. Parameters: arr : array-like or string to be searched. substring : substring to search for. start, end : [int, option
1 min read
Python | Pandas Index.isna() Index.isna() function in pandas detects missing values i.e., NaN or None in a pandas.Index. It behaves identically to Index.isnull(), as both are aliases of each other. It returns a boolean array, where:True indicates a missing value.False indicates a valid (non-null) value.Example:Pythonimport pand
2 min read
Python | Pandas Index.where Pandas Index is an immutable ndarray implementing an ordered, sliceable set. It is the basic object which stores the axis labels for all pandas objects. Pandas Index.where function return an Index of same shape as self and whose corresponding entries are from self where cond is True and otherwise ar
2 min read
Python | Pandas Index.insert() Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.insert() function make new Index inserting new item at location. This fun
2 min read