In this post, we will see different techniques for how to get index of item in a list in python. So without further ado let’s get started.
Techniques To Get Index Of Item In A List In Python
Let’s look at different ways to the index of an item in a list.
1. By Using Index() method
The index() method can be used to get the index of an element inside the list.
element : element to be searched inside the list.
start(optional) : Search element from this index.
end(optional) : Search upto this index.
# A list of items >>> items = ["cat","dog","dear","lion"] # Find index of a item >>> items.index("dear") 2 >>> items.index("lion") 3
If the element did not exist inside the list. it will throw an ValueError.
>>> items.index("lions") # it will throw error VALUE ERROR
So to avoid any type of error. its better to wrap your code inside the try-except block.
>>> try: print(items.index("lions")) except: print("Item Did nt exists") Item Did nt exists
2. By Using For-loop
In this code example, we used a for-loop to find the index of an element.
Here is the algorithm.
- We first iterate through each element of the list.
- On each iteration, we check if the current element matches with the element to be searched.
- If yes, we return its index.
#program to Get Index Of Item In A List In Python def find_index(items,item): # Function to find index of a item from a list of items for i in range(len(items)): # iterate through list of items if items[i] == item: # if we find item then return its index return i items = ["cat","dog","dear","lion"] print(find_index(items,"dog")) print(find_index(items,"dogs")) # it will return None
3. Find All Indices Of A Item
In the below code, we used for loop to find all indexes of the element.
The code is mostly the same as the previous example. but instead of returning the index, it stores inside the list and returns that list.
#Function To Get Index Of Item In A List In Python def find_index(items,item): indexes =  # list to store the indexes # Function to find index of a item from a list of items for i in range(len(items)): # iterate through list of items if items[i] == item: # if we find item then append its index to list indexes.append(i) return indexes items = ["cat","dog","dear","dog"] print(find_index(items,"dog"))
Here is the summary of whole tutorial in one picture.
Also read about how to remove duplicates from the list.