Python: Check Index of an Item in a List

Introduction

Lists are useful in different ways compared to other datatypes because of how versatile they are. In this article we'll take a look at one of the most common operations with lists - finding the index of an element.

We will take a look at different scenarios of finding an element, i.e. finding the first, last, and all occurrences of an element. As well as what happens when the element we're looking for doesn't exist.

Using the index() Function

All of the operations we mentioned in the last paragraph can be done with the built-in index() function. The syntax for this function is index(element[, start[, end]]).

The element parameter naturally represents the element we're looking for. The start and end parameters are optional and represent the range of indices in which we look for the element.

The default value for start is 0 (searching from the beginning), and the default value for end is the number of elements in the list (searching to the end of the list).

The function returns the first position of the element in the list that it could find, regardless of how many equal elements there are after the first occurrence.

Finding the First Occurrence of an Element

Using the index() function without setting any values for start and end will give us the first occurrence of the element we're looking for:

my_list = ['a', 'b', 'c', 'd', 'e', '1', '2', '3', 'b']

first_occurrence = my_list.index('b')
print("First occurrence of 'b' in the list: ", first_occurrence)

Which would give us the expected output:

First occurrence of 'b' in the list: 1

Finding All Occurrences of an Element

To find all occurrences of an element, we can use the optional parameter start so that we search in only certain segments of the list.

For example, let's say that we would the first occurrence of an element at index 3. In order to find the next one, we would need to continue our search for the first appearance of that element after index 3. We would repeat this process, changing where our search begins, as long as we found new occurrences of the element:

my_list = ['b', 'a', 2, 'n', False, 'a', 'n', 'a']

all_occurrences = []
last_found_index = -1
element_found = True

while element_found:
    try:
        last_found_index = my_list.index('a', last_found_index + 1)
        all_occurrences.append(last_found_index)
    except ValueError:
        element_found = False
    
if len(all_occurrences) == 0:
    print("The element wasn't found in the list")
else:
    print("The element was found at: " + str(all_occurrences))

Running this code would give us:

The element was found at: [1, 5, 7]

We had to use a try block here, since the index() function throws an error when it can't find the specified element in the given range. This might be unusual to developers who are more used to other languages since functions like these usually return -1/null when the element can't be found.

However, in Python we have to be careful and use a try block when we use this function.

Another, more neat way of doing this same thing would be by using list comprehension and ignoring the index() function altogether:

my_list = ['b', 'a', 2, 'n', False, 'a', 'n', 'a']

all_occurrences = [index for index, element in enumerate(my_list) if element == 'a']

print("The element was found at: " + str(all_occurrences))

Which would give us the same output as before. This approach has the added benefit of not using the try block.

Finding the Last Occurrence of an Element

If you need to find the last occurrence of an element in the list, there are two approaches you can use with the index() function:

  • Reverse the list and look for the first occurrence in the reversed list
  • Go through all the occurrences of the element, and only keep track of the last occurrence

Regarding the first approach, if we knew the first occurrence of the element in a reversed list, we could find the position of the last occurrence in the original one. More specifically, we can do this by subtracting reversed_list_index - 1 from the length of the original list:

my_list = ['b', 'a', 2, 'n', False, 'a', 'n', 'a']

reversed_list_index = my_list[::-1].index('n')
# or alteratively:
# reversed_list_index2 = list(reversed(my_list)).index('n')

original_list_index = len(my_list) - 1 - reversed_list_index

print(original_list_index)

Which would give us the desired output:

6

As for the second approach, we could tweak the code we used to find all occurrences and only keep track of the last occurrence we found:

my_list = ['b', 'a', 2, 'n', False, 'a', 'n', 'a']

last_occurrence = -1
element_found = True

while element_found:
    try:
        last_occurrence = my_list.index('n', last_occurrence + 1)
    except ValueError:
        element_found = False
    
if last_occurrence == -1:
    print("The element wasn't found in the list")
else:
    print("The last occurrence of the element is at: ", last_occurrence)

Which would give us the same output:

6

Conclusion

We have taken a look at some of the most common uses for the index() function, and how to avoid it in some cases.

Keep the potentially unusual behavior of the index() function in mind, where it throws an error instead of returning -1/None when an element isn't found in the list.