Get the index of an item in a list python

In this code snippet, we are going to describe the methods that can be used to get the index of an item that exists in a python list.

#define a list
items = ["Jack", "Lori", "Richard", "Gavin"]

#get the index of Richard
index = items.index("Richard")


# -> 2

As we all know that we can access the items of a python list using its index. So if you want to access or delete an item, you need its position in the list. Here, we are using the index() method of the list to get the index of an item.

The above code snippet process:

1. We have created a list named items that contain multiple items in it.

2. We have a name - Richard and we want to find the index of this in the given list.

3. To get the index we use the index() method and pass the item to it as a parameter.

4. The above process returns the index of the item in the list.

Note that, the index() method will return the index of the very first item in the list it matches with. If you want to get indexes of all items based on an item, then you will have to use another method.

What if the item does not exist in the list

If you are using the index() function to get the index of an item in the list and the item does not exist in the list. It will throw an exception in that case.

The below code will throw an exception as the item does not exist in the list.

my_list = ["Barket", "Beam", "Handricks", "Belson"]

#get the index of Peter
index = my_list.index("Peter")

The exception details:

Traceback (most recent call last):
  File "", line 4, in <module>
    index = my_list.index("Peter")
ValueError: 'Peter' is not in list

To handle the exception, you can use Exception Handling in python.

my_list = ["Barket", "Beam", "Handricks", "Belson"]

    index = my_list.index("Peter")
except Exception as e:
    print("Item does not exist in the list")
my_list = ["Barket", "Beam", "Handricks", "Belson"]

#get the index of Beam
indexes = [index for index, item in enumerate(my_list) if item == 'Beam']

# -> 1
Item index from a list can also be found using for loop and enumerate() method. This returns all the indexes of an item from a list. We are printing the very first index of item using this code.
Was this helpful?