Python Negative index of Element in List (original) (raw)

Last Updated : 29 Jan, 2025

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.

Python `

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:

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.

Python `

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:

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.

Python `

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:

Similar Reads