Find an Index of an Item in a List in Python

The index function returns the position of an item in a list. The function takes up to three parameters. One of them is required and the other two are optional.

Objects in Python are zero-index, so the indexing starts from 0. If you run the code, the above code returns 1 as an index of the list.

The first position of an item

The values in the list from the previous example are unique. You can add another element that’s a duplicate.

Now, you have two “two” values. If you run the code, it will return the index of the first element, so the result will be the same as before.

1

The last position of an item

The index function looks for the value from the beginning of a list. If you want to iterate over a list from the end to the beginning, you have to reverse elements in the list. You can do that by using the reverse function.

Using only the reverse function will give us 0 as the result, so it’s not exactly what we expected. We have to do some math.

Let’s take a look at the result inside the print function.

There are 4 elements in the list. From this number, we subtract the index of the reversed list, which is 0. This will give us 4. Because indexing starts from 0 and not 1, we have to subtract one to get the index of the last “two” elements.

3

All positions of an item

The index function iterates through the list until it finds the matching element. When it finds it, it stops. If you want to find all matching elements, you can use the list comprehension and the enumerate function.

This code will print a list of indexes. In our case, there are two.

[1, 3]

If you want, you can do it in a single line.

Handle exceptions if there is no item

So far, we have dealt with lists that contain at least one matching item. Let’s see what’s going to happen if there is no such element inside the list.

If you run this code, Python is going to raise an error.

ValueError: 'five' is not in list

There are two ways we can deal with it.

Check if there is an element inside the list

There are a few approaches you can use to check if the specified value is inside a list. Probably the most “pythonic” way to do it is to use the “in” word.

This code returns nothing because there is no “five” inside the list.

Handle exception using try .. except

Another way to handle the exception is to use try .. except.

In this case, there is no “five” inside the list, so Python returns code under except clause.

No such value in the list!

Checking the x number of items

At the beginning of the tutorial, I wrote that the index function takes two optional parameters.

The index function checks every element of a list until it finds a match. If we are using long lists that can take a lot of time.

Take a look at this example. This code searches the entire list for a match.

It has to iterate almost the entire list to find a match. If you can estimate where Python should search for the value, you can lower the time needed to do this operation.

The search starts from 900,000, instead of 0. This results in reducing the operation by about 10x.

Of course, for such small numbers, it’s hard to see which one is actually faster. We can quickly use the timeit module to check the execution time of small bits of code.

The last parameter tells the interpreter how many times the code should be executed. In our case, it’s 1000 times.

If you run it, you’ll see that the second part of the code is executed approximately 10 times faster than the first one.

11.836976
1.1330223000000004

Let’s create a benchmark where we can see these numbers for multiple different values and display them inside a chart. To draw a chart we are going to use the matplotlib module.

This code is run inside a loop for 100, 200, …, 1000 times. Take a look at how much time each iteration took for different numbers.

NumberIndex (Full)Index (Part)
1001.120.11
2002.240.22
3003.360.33
4004.480.45
5005.630.55
6006.740.66
7007.930.78
8008.960.88
90010.071.00
100011.181.16

At the end of the code, the show function displays the chart.

Using NumPy

NumPy adds support for large multi-dimensional arrays. This library can also be used to find an index in a Python list.

The returned index equals 1, as the first matching value is in the second position. The list number is converted to the NumPy array.

You can easily modify it to return all matching positions.

Now, index 1 and 3 is returned.

[1 3]

Using Pandas

Another popular library for data manipulation is Pandas. This code displays the first matching index.

If you want to return all matching indexes, remove [0] from the last line of the code.

Benchmark

For simple examples, it doesn’t matter which form you are using to find indexes, but it makes a huge difference for a big number of calculations or big data.

That’s why I wanted to show the differences between these three methods: index function, NumPy, and Pandas.

Run this code to get a list of values and a chart.

Let’s take a look at how the data looks inside a table.

NumberIndex (Full)NumPyPandas
1001.120.090.11
2002.260.100.23
3003.340.160.33
4004.490.210.45
5005.590.260.54
6006.660.330.67
7007.820.370.78
8009.020.430.89
90010.050.480.99
100011.150.531.11

It will be easier to visualize that using a chart.

You can see that both NumPy and Pandas are much quicker than the standard index function. In this case, NumPy is the quickest way (20x) as it works great with smaller data sets.