Python - Negative index of Element in List
We are given a list we need to find the negative index of that element. For example, we are having a list li = [10, 20, 30, 40, 50] and the given element is 30 we need to fin the negative index of it so that given output should be -3.
Using index()
index
()
method in Python searches for the first occurrence of a specified element in a list and returns its index. In this example s.index(ele)
directly finds and returns the index of the element ele
in the list s.
li = [10, 20, 30, 40, 50]
ele = 30
# Find the positive index and convert it to negative
p = li.index(ele)
n = -(len(li) - p) - 1
print(f"Negative index of {ele}: {n}")
Output
Negative index of 30: -3
Explanation:
- Code reverses list using
li[::-1]
and then usesindex()
method to find index of the element from reversed list. - Negative index is calculated by subtracting index of element from length of the list adjusted for a negative index.
Using reversed()
and index()
Using reversed
()
to reverse list and index()
to find the index of element within reversed list provides an efficient way to determine the negative index.
li = [10, 20, 30, 40, 50]
ele = 30
# Reverse the list and find index
n = -list(reversed(li)).index(ele) - 1
print(f"Negative index of {ele}: {n}")
Output
Negative index of 30: -3
Explanation:
- List is reversed using
reversed()
and theindex()
function is used to find index of the element in the reversed list. - Negative index is obtained by negating the result of the index in the reversed list and subtracting one to adjust for the reversed order.
Using a loop
Manually iterating through list in reverse order we can find the index of the given element loop checks each element starting from the last one and when the element is found it calculates the negative index based on position from the end.
li = [10, 20, 30, 40, 50]
ele = 30
# Loop through the list and calculate the negative index
n = -1
for i in range(len(li)-1, -1, -1):
if li[i] == ele:
n = -(len(li) - i)
break
print(f"Negative index of {ele}: {n}")
Output
Negative index of 30: -3
Explanation:
- Loop iterates over list in reverse order starting from last element and moving towards the first. It checks each element to see if it matches the target element (
ele
). - When the element is found the negative index is calculated by subtracting the current index from the total length of the list ensuring the result is in negative form.