We can get the index of an element in a Python list using the `index` method available on lists. Call this method by specifying what to search. If it is available, we get its index; otherwise, we get a value error. We can also set when to start and stop searching while searching for an element.
Here's how to search for indexes of elements in a list.
l = ['apple', 'orange', 'mango'] l.index('orange') >>> 1
In the above example the list comprises three fruites. In this list we search the index of orange. The output shows the position of orange in the list is one.
Python uses zero-based index system. This is why the second element of the list has the index of 1.
Suppose we try to get the index of grapes in this list, we'll get a value error instead. If an element does not exist on the list, the index method will always through a value error. The error message will tell us which element was searched but was not available. This is very useful when debugging large codebases.
Here's how it works.
l.index('grapes') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: 'grapes' is not in list
The index method is a convenient way to find the index of an element. Yet, before we use it in our scripts, we should be aware of a couple of things.
Searching the index of elements can be slow if the list is very long.
Large lists are very common in data-driven applications. Yet, it is not advisable to find the index of an element in such a list. It's better to avoid such operations at all costs.
Here's an example. Suppose we have a list of one million records and we want to find out the index of 999,999 in this list will take some significant time. This is becuse, the index method search for elements one-by-one. It needs to go through all the 999,999 elements to find the index of the same.
Index searching in Python list is of order O(n). Which means it doesn't become slower and slower with the size of the list.
Index search in Python lists have a linear time-complexity.
Use start and end parameters to speed up index search.
One way to improve the search is specifying the start and end parameters. For instance, by setting the start value as 999,000 and the end value as 1,000,000, we can narrow the search to only 1000 elements.
l = list(range(1000000)) l.index(999999,999000,1000000)
Besides speeding up, start and end parameters are also helpful for implementing search with complex logic.
The index method only finds one (the first) element that matches the search.
Suppose there is more than one matching element in the list, and we need the indexes of both of them. The index method of the list won't help in this situation. It'll always return the first element's index that matches the search.
l = ['a', 'b', 'a', 'c'] l.index('a') # we expect 0 and 2 >>> 0
We can use list comprehensions to get the index of more than one match in the list. List comprehensions are one of the beautiful things about Python.
l = ['a', 'b', 'a', 'c'] [ix for ix, el in enumerate(l) if el == 'a'] >>> [0, 2]
Handle the exception when there's no valid match.
When there's no match, instead of returning None Python interpreter raises a Value Error. This is okay if you're experimenting. But this will break your code in real applications. You must put excepting handling to avoid this.
l = ['apple', 'orange', 'mango'] try: l.index('grapes') except ValueError: print("This list does not contain grapes")
Not a Medium member yet? Please use this link to become a member because I earn a commission for referring at no extra cost for you.