Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Negative index of Element in List
Getting the negative index of an element in a list helps you find the position from the end. Python allows negative indexing where -1 refers to the last element, -2 to the second last, and so on.
Understanding Negative Indexing
In Python, negative indices count backward from the end of the list:
Converting Positive Index to Negative Index
To find the negative index of an element, use the formula: negative_index = positive_index - len(list)
my_list = [52, 47, 18, 22, 23, 57, 13]
print("The list is:")
print(my_list)
my_key = 22
print("The value of key is:")
print(my_key)
# Find positive index first
positive_index = my_list.index(my_key)
print("Positive index:", positive_index)
# Convert to negative index
negative_index = positive_index - len(my_list)
print("Negative index:", negative_index)
The list is: [52, 47, 18, 22, 23, 57, 13] The value of key is: 22 Positive index: 3 Negative index: -4
Alternative Method
You can also calculate the distance from the end directly ?
my_list = [52, 47, 18, 22, 23, 57, 13]
my_key = 22
# Distance from end = total length - positive index
distance_from_end = len(my_list) - my_list.index(my_key)
print("Distance from end:", distance_from_end)
# Verify using negative indexing
print("Element at negative index -4:", my_list[-4])
Distance from end: 4 Element at negative index -4: 22
Handling Multiple Occurrences
The index() method returns only the first occurrence. For multiple occurrences, use list comprehension ?
numbers = [10, 22, 30, 22, 50]
target = 22
# Find all positive indices
positive_indices = [i for i, x in enumerate(numbers) if x == target]
print("All positive indices:", positive_indices)
# Convert to negative indices
negative_indices = [i - len(numbers) for i in positive_indices]
print("All negative indices:", negative_indices)
All positive indices: [1, 3] All negative indices: [-4, -2]
Conclusion
To find the negative index of an element, use positive_index - len(list). The index() method finds the positive index, then subtract the list length to get the negative equivalent. This helps access elements from the end of the list.
