Python How to Find Index in a List: The index() Function

To find the index of a list element in Python, use the built-in index() method.

For example, let’s find the first string that equals “Bob” in a list of strings:

names = ["Alice", "Bob", "Charlie"]

names.index("Bob") # Returns 1

To find the index of a character in a string, use the index() method on the string.

For example, let’s find the first occurrence of the letter w in a string:

"Hello world".index("w") # returns 6

This is the quick answer.

In this guide, we are going to take a deeper dive into finding the index of an element in Python.

You are going to learn:

  • How the index() method works.
  • How to get multiple indexes of all similar elements.
  • How to find the index of a list element.
  • How to find the index of a character in a string.

The index() Method in Python

In Python, a list has a built-in index() method.

This method returns the index of the first element that matches with the parameter.

The syntax for the index() function is as follows:

list.index(obj)

Where:

  • list is the list we are searching for.
  • obj is the object we are matching with.

Let’s see some examples of using the index() method in Python.

How to Find the Index of a List Element in Python

You can use the index() method to find the index of the first element that matches with a given search object.

For instance, let’s find the index of “Bob” in a list of names:

names = ["Alice", "Bob", "Charlie"]

names.index("Bob") # Returns 1

The index() method returns the first occurrence of an element in the list. In the above example, it returns 1, as the first occurrence of “Bob” is at index 1.

But this method has a little problem you need to understand.

If the element you are searching for does not exist, this method throws an error that crashes the program if not handled correctly.

For example, let’s search for “David” in the list of names:

names = ["Alice", "Bob", "Charlie"]

idx = names.index("David")

Output:

ValueError: 'David' is not in list

You certainly don’t want your program to crash when searching for a non-existent value.

To fix this issue, you should check that the element is in the sequence, to begin with. To do this, use the in statement with a simple if-else statement.

For example:

names = ["Alice", "Bob", "Charlie"]

if "David" in names:
    idx = names.index("David")
else:
    print("Not found.")

Output:

Not found.

Now the above code no longer throws an error. The index search does not even start if the item is not there.

Now you know how to use the index() method to find an index of an object in a list.

Next, let’s take a look at how you can use a similar approach to finding the index of a character in a string.

How to Find the Index of a String Character in Python

To find an index of a character in a string, follow the same procedure as finding an index in a list.

  • Check if the character is in the string using the in statement.
  • Find the index of the character using the index() method of a string.

For example:

sentence = "Hello world"

if "x" in sentence:
    idx = sentence.index("x")
else:
    print("Not found.")

Output:

Not found.

With strings, you can also search for longer substrings or words.

For example, let’s find the index of a substring “wor” in “Hello world”:

sentence = "Hello world"

substr = "wor"

if substr in sentence:
    idx = sentence.index(substr)
    print(idx)
else:
    print("Not found.")

Output:

6

This returns the starting position of the substring “wor”.

Now you understand how to use the index() method in Python.

However, this method only returns the first index. Let’s take a look at how you can get all the indexes instead.

How to Get All Indexes of a List in Python

In the previous examples, you have seen how to get the first index of an element that is equal to the object we are searching for.

However, sometimes you might want to find the indexes of all the elements that equal something.

To get all the indexes:

  1. Couple the elements of a list with an index using the enumerate() function.
  2. Loop over the enumerated elements.
  3. Check if the index, item pair’s item matches with the object you are searching for.
  4. Add the index to a result list.

Here is a generator function that does exactly that:

def indexes(iterable, obj):
    result = []
    for index, elem in enumerate(iterable):
        if elem == obj:
            yield index

Or if you want to use a shorthand, you can also use a generator comprehension:

def indexes(iterable, obj):
    return (index for index, elem in enumerate(iterable) if elem == obj)

Anyway, let’s use this function:

names = ["Alice", "Alice", "Bob", "Alice", "Charlie", "Alice"]
idxs = indexes(names, "Alice")

print(list(idxs))

Output:

[0, 1, 3, 5]

As you can see, now this function finds all the indexes of “Alice” in the list.

You can also call it for other iterables, such as a string:

sentence = "Hello world"
idxs = indexes(sentence, "l")

print(list(idxs))

Output:

[2, 3, 9]

Conclusion

Today you learned how to get the index of an element in a list in Python.

You also saw how to get all the indexes that match with an object.

To recap, use the index() method to find the index of an element in Python. You can use it the same way for lists and strings. It finds the first occurrence of a specified element in the sequence.

To get all the indexes:

  • Implement a function that couples each element with an index.
  • Loop through the coupled elements.
  • Pick the indexes of the elements that match with the search object.
Scroll to Top