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")
print(index)
# -> 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.
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 "main.py", 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"]
try:
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']
print(indexes[0])
# -> 1
- Remove an item from python list using its index
- Get last item or value from a List in python
- Get the index of the list inside python for loop
- Get a random item from a List in Python
- Pandas - Get index values of a DataFrame as a List
- Add two list items with their respective index in python
- Find all indexes of an item in a list using python