You are currently viewing Negative Index of List in Python

How to get a negative index of an element from the list in Python? A negative index of a list in Python refers to accessing elements in a list by counting from the end of the list rather than from the beginning. You can use negative indexing to access elements of a list or string from the end instead of the beginning. The index -1 refers to the last element in the list, and -2 refers to the second last element.

Advertisements

You can represent the negative index of elements in a list in Python using many ways, for example, by using index() & len(), enumerate(), For Loop & range(), and ~ operator + list slicing + index() methods. In this article, I will explain the concept of a negative index of a list by using all these methods with examples.

1. Quick Examples of Negative Index of List

If you are in a hurry, below are some quick examples of a negative index of a list.


# Quick examples of negative index

# Initialize list
mylist = [3, 7, 4, 2, 8, 6, 9, 5]

# Example 1: Using a negative index of elements in list
# Using index() + len() method
element = 8
neg_index = mylist.index(element) - len(mylist)

# Example 2: Loop over the list 
# Using enumerate()
element = 6
for i, val in enumerate(mylist):
    if val == element:
        neg_index = -(len(mylist) - i)
        break

# Example 3: Using for loop and range function 
# To find the negative index
element = 6
for i in range(len(mylist)-1, -1, -1):
    if mylist[i] == element:
        neg_index = -len(mylist) + i
        break

# Example 4: Using ~ operator + list slicing + index()
element = 4
neg_index = ~mylist[::-1].index(element)

# Example 5: iterate over the list   
element = 8
index = -1  
for i, elem in enumerate(mylist):
    if elem == element:
        index = -(i+1)
        break

2. Negative index of a List Using index() & len() Method

You can use negative indices to access elements of a list from the ending point. In a list, the index of the last element refers to -1, the second element from the last refers to -2, and so on. You can use the index() method along with the len() function to get the index of the list element from the ending point.


# Initialize list
mylist = [3, 7, 4, 2, 8, 6, 9, 5]
print("Original list: ", mylist)

# Initializing Element
element = 8
 
# Get negative index of specified element in the list
# Using index() & len() method
neg_index = mylist.index(element) - len(mylist)
print('Negative index of', element, ':', neg_index)

Yields below output.

python list negative index

3. Negative index of Element in List Using enumerate() and a loop

You can also find the negative index of an element in a list using the enumerate() function and a for loop in Python. For example, the enumerate() function is used to loop over the list mylist. For each element in the list, the loop checks, if the element is equal to the element variable, initialized earlier.

If the element is found, the negative index is calculated by subtracting the length of the list from the current index i. The code then prints the negative index of the element and breaks out of the loop using the break statement.


# Initialize list
mylist = [3, 7, 4, 2, 8, 6, 9, 5]
print("Original list: ", mylist)

# Initializing Element
element = 6

# Loop over the list 
# Using enumerate()
for i, val in enumerate(mylist):
    if val == element:
        # calculating negative index 
        # Using length of list and current index
        neg_index = -(len(mylist) - i)
        break
print('Negative index of', element, ':', neg_index)

Yields below output.

python list negative index

4. Using a For Loop and range() Function

You can also get the negative index of an element in a list using a for loop and the range() function. For instance, you start the range() function from the last index of the list (i.e., len(my_list)-1) and iterate backward to the first index (i.e., -1), with a step of -1 to traverse the list in reverse order. Inside the loop, you check each element of the list to see if it matches the target element element.

If you find a match, you calculate the negative index of the element using the formula -len(my_list) + i, where i is the index of the element. you can then print out the result and break out of the loop using the break statement.


# Initialize list
mylist = [3, 7, 4, 2, 8, 6, 9, 5]
print("Original list: ", mylist)

# Initializing Element
element = 6

# Using for loop and range function 
# To find the negative index
for i in range(len(mylist)-1, -1, -1):
    if mylist[i] == element:
        neg_index = -len(mylist) + i
        break
        
print('Negative index of', element, ':', neg_index)

Yields the same output as above.

5. Negative index of Element in List Using ~ operator + list slicing + index()

Use the ~ (tilde) operator along with list slicing and the index() method. The code reverses the original list using list slicing (mylist[::-1]) to create a new list with the elements in reverse order. The index() method is then used to find the first occurrence of the target element element in this reversed list.

The result of index() is the index of element relative to the reversed list. To convert this to the negative index relative to the original list, you can use the ~ operator to bitwise negate the index value. This results in a negative number that represents the index of element the original list. The code then prints out the result using an f-string, which displays the negative index of element.


# Initialize list
mylist = [3, 7, 4, 2, 8, 6, 9, 5]
print("Original list: ", mylist)

# Initializing Element
element = 4

# Using ~ operator + list slicing + index()
neg_index = ~mylist[::-1].index(element)
print('Negative index of', element, ':', neg_index)

Yields below output.

Here is another example


# Initialize list
mylist = [3, 7, 4, 2, 8, 6, 9, 5]
print("Original list: ", mylist)

# Initializing Element
element = 8
# Initialize index variable
index = -1

# Iterate over the list       
for i, elem in enumerate(mylist):
    if elem == element:
        index = -(i+1)
        break
print('Negative index of', element, ':', index)

Yields below output.

Conclusion

In this article, I have explained the negative index of elements in a list Python by using index() & len(), enumerate(), For Loop & range(), and ~ operator+list slicing+index() methods with examples.

Happy Learning !!