Python List index()

In this tutorial, you will learn how to find the index of an element in a Python list. A list is an array. So if you are new to Python, treat the list the same as you treat an array in other programming languages.

Python built-in index() function

To find the index of an element in a list the most straightforward way is by using  built-in index()  function.

list.index(x[, start[, end]])

This function returns a zero-based index of the first item whose value is equal to x. Meaning it considers the index of the first element 0. It raises a ValueError if there is no matched item in the list.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list, but the index is still from the beginning of the list.

As an example, consider the following list of animals and giraffe as our search element.

animals = [ "monkey" , "dog" , "cat", "giraffe", "horse"]
animals.index("giraffe")

This gives 3 as output, as the index starts with 0.

Return an index of the first matched element

The search stops as soon as a match is found for the element. So if there are more elements and you need all the indexes, thenindex() function does not help.

so, the following will never give 1.

["5", "5"].index("5") # gives 0

If you want the subsiding occurrences, use the start and stop parameters accordingly. To get all the indexes of the match elements, useenumerate.

[idx for idx, e in enumerate(["k", "j", "k"]) if e == "k"]

Output: 

[0, 2]

An exception is raised if  there is no match

An  ValueError exception is thrown if no match is found. Look at the following code example. As “ant” is not on the list, it will throw an exception.

animals = [ "monkey" , "dog" , "dog", "dog", "horse"]
animals.index("ant")

Error:

ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_7132\1767255224.py in <module>
      1 animals = [ "monkey" , "dog" , "dog", "dog", "horse"]
----> 2 animals.index("ant")

ValueError: 'ant' is not in list

Note: The parameters are case-sensitive, and index() would return a ValueError even if the element is present but in a different case. Use the .upper() or .lower() methods in case you are not sure about the case.

If you do not want your program to crash, then handle this exception in a try-catch block. Or maybe you do not want the index of the element then you can use in  the operator to check the element without exception. Or a combination of both to avoid exceptions and have the index.

Time complexity increases linearly

The index function finds the match by checking every element of the list until the match is found. Thus, for a smaller list, this is a good choice. But if you are dealing with huge lists and you are not sure whether the match will be found or not, then this function is not. This will increase the time cost of your code. So the longer the list, the more amount of time it will take.

To avoid the time complexity, you can narrow down the search by giving the start and end parameters. Only if you have some sort of idea of the element index. Look at the following code

time_eval = {
'Time of one million list search': timeit.timeit('l.index(999_999)', setup='l = list(range(0, 1_000_000))', number=1000),
'Time of narrowed down search': timeit.timeit('l.index(999_999, 999_990, 1_000_000)', setup='l = list(range(0, 1_000_000))', number=1000),
}
time_eval

Output:

{'Time of one million list search': 11.58299820000002, 
'Time of narrowed down search': 0.00019800000006853224}

You can clearly see the time difference. Because the second search is only through 10 elements instead of the whole.

Conclusion

That concludes this tutorial. I hope it was helpful to you. If you have any questions, please leave them in the comments section. I would be happy to help. Additionally, please check out our Python tutorials page, where we regularly post content for both beginners and advanced developers. You’re sure to find something interesting there.