Open In App

What is Negative Indexing in Python?

Last Updated : 02 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Output
50
40

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)

Output
n
h

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:])  

Output
[20, 25]

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])   

Output
[5, 6]
6

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



Next Article
Article Tags :
Practice Tags :

Similar Reads