Skip to content

Python List Index: Find First, Last or All Occurrences

Python List Index Find First, Last or All Occurrences Cover Image

In this tutorial, you’ll learn how to use the Python list index method to find the index (or indices) of an item in a list. The method replicates the behavior of the indexOf() method in many other languages, such as JavaScript. Being able to work with Python lists is an important skill for a Pythonista of any skill level. We’ll cover how to find a single item, multiple items, and items meetings a single condition.

By the end of this tutorial, you’ll have learned:

  • How the Python list.index() method works
  • How to find a single item’s index in a list
  • How to find the indices of all items in a list
  • How to find the indices of items matching a condition
  • How to use alternative methods like list comprehensions to find the index of an item in a list

Python List Index Method Explained

The Python list.index() method returns the index of the item specified in the list. The method will return only the first instance of that item. It will raise a ValueError is that item is not present in the list.

Let’s take a look at the syntax of the index() method:

# The list.index() Method Explained
list.index(
    element,    # The element to search for
    start,      # The index to start searching at
    end         # The index to end searching at
)

Let’s break these parameters down a little further:

  • element= represents the element to be search for in the list
  • start= is an optional parameter that indicates which index position to start searching from
  • end= is an optional parameter that indicates which index position to search up to

The method returns the index of the given element if it exists. Keep in mind, it will only return the first index. Additionally, if an item doesn’t exist, a ValueError will be raised.

In the next section, you’ll learn how to use the .index() method.

Find the Index Position of an Item in a Python List

Let’s take a look at how the Python list.index() method works. In this example, we’ll search for the index position of an item we know is in the list.

Let’s imagine we have a list of the websites we open up in the morning and we want to know at which points we opened 'datagy'.

# Finding the index of an item in a list
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(a_list.index('datagy'))

# Returns: 0

We can see that the word 'datagy' was in the first index position. We can see that the word 'twitter' appears more than once in the list. In the next section, you’ll learn how to find every index position of an item.

Finding All Indices of an Item in a Python List

In the section above, you learned that the list.index() method only returns the first index of an item in a list. In many cases, however, you’ll want to know the index positions of all items in a list that match a condition.

Unfortunately, Python doesn’t provide an easy method to do this. However, we can make use of incredibly versatile enumerate() function and a for-loop to do this. The enumerate function iterates of an item and returns both the index position and the value.

Let’s see how we can find all the index positions of an item in a list using a for loop and the enumerate() function:

# Finding all indices of an item in a list
def find_indices(search_list, search_item):
    indices = []
    for (index, item) in enumerate(search_list):
        if item == search_item:
            indices.append(index)

    return indices

a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(find_indices(a_list, 'twitter'))

# Returns: [1, 3]

Let’s break down what we did here:

  1. We defined a function, find_indices(), that takes two arguments: the list to search and the item to find
  2. The function instantiates an empty list to store any index position it finds
  3. The function then loops over the index and item in the result of the enumerate() function
  4. For each item, the function evaludates if the item is equal to the search term. If it is, the index is appended to the list
  5. Finally, this list is returned

We can also shorten this list for a more compact version by using a Python list comprehension. Let’s see what this looks like:

# A shortened function to return all indices of an item in a list
def find_indices(search_list, search_item):
    return [index for (index, item) in enumerate(search_list) if item == search_item]

a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(find_indices(a_list, 'twitter'))

# Returns: [1, 3]

One of the perks of both these functions is that when an item doesn’t exist in a list, the function will simply return an empty list, rather than raising an error.

Find the Last Index Position of an Item in a Python List

In this section, you’ll learn how to find the last index position of an item in a list. There are different ways to approach this. Depending on the size of your list, you may want to choose one approach over the other.

For smaller lists, let’s use this simpler approach:

# Finding the last index position of an item in a list
def find_last_index(search_list, search_item):
    return len(search_list) - 1 - search_list[::-1].index(search_item)

a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']

print(find_last_index(a_list, 'twitter'))

# Returns: 3

In this approach, the function subtracts the following values:

  • len(search_list) returns the length of the list
  • 1, since indices start at 0
  • The .index() of the reversed list

There are two main problems with this approach:

  1. If an item doesn’t exist, an ValueError will be raised
  2. The function makes a copy of the list. This can be fine for smaller lists, but for larger lists this approach may be computationally expensive.

Let’s take a look at another approach that loops over the list in reverse order. This saves the trouble of duplicating the list:

# A less simple, but more memory efficient way of finding the last index of an item
def find_last_index(search_list, search_item):
    i = len(search_list) - 1
    while i >= 0:
        if search_list[i] == search_item:
            return i
        else:
            i -= 1
            
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']

print(find_last_index(a_list, 'twitter'))

# Returns: 3

In the example above we loop over the list in reverse, by starting at the last index. We then evaluate if that item is equal to the search term. If it is we return the index position and the loop ends. Otherwise, we decrement the value by 1 using the augmented assignment operator.

Index of an Element Not Present in a Python List

By default, the Python list.index() method will raise a ValueError if an item is not present in a list. Let’s see what this looks like. We’ll search for the term 'pinterest' in our list:

# Searching for an item that doesn't exist
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']

print(a_list.index('pinterest'))

# Raises: ValueError: 'pinterest' is not in list

When Python raises this error, the entire program stops. We can work around this by nesting it in a try-except block.

Let’s see how we can handle this error:

# Handling an error when an item doesn't exist
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']

try:
    print(a_list.index('pinterest'))
except ValueError:
    print("Item doesn't exist!")

# Returns: Item doesn't exist!

Working with List Index Method Parameters

The Python list.index() method also provides two additional parameters, start= and stop=. These parameters, respectively, indicate the positions at which to start and stop searching.

Let’s say that we wanted to start searching at the second index and stop at the sixth, we could write:

# Using Start and Stop Parameters in list.index()
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']

print(a_list.index('twitter', 2, 6))

# Returns: 3

By instructing the method to start at index 2, the method skips over the first instance of the string 'twitter'.

Finding All Indices of Items Matching a Condition

In this final section, we’ll explore how to find the index positions of all items that match a condition. Let’s say, for example, that we wanted to find all the index positions of items that contain the letter 'y'. We could use emulate the approach above where we find the index position of all items. However, we’ll add in an extra condition to our check:

# Finding Indices of Items Matching a Condition
def find_indices(search_list, search_item):
    return [index for (index, item) in enumerate(search_list) if search_item in item]


a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(find_indices(a_list, 'y'))

# Returns:
# [0, 5]

The main difference in this function to the one shared above is that we evaluate on a more “fuzzy” condition.

Conclusion

In this tutorial, you learned how to use the index list method in Python. You learned how the method works and how to use it to find the index position of a search term. You also learned how to find the index positions of items that exist more than once, as well as finding the last index position of an item.

Finally, you learned how to handle errors when an item doesn’t exist as well as how to find the indices of items that match a condition.

Additional Resources

To learn more about related topics, check out the tutorials below:

Leave a Reply

Your email address will not be published.