Finding The Index Of An Item In A List Python

Do you want to know the index of an item in a list using Python? In this article, I will show you how you can find the index of an item in a list easily and quickly.

In Python, the index() method in the list class can be used to find the index of items in the list. You can also use the list comprehension method and the enumerate function to get the index of an item in a list in Python. Let dive deep with examples for all these methods.

But the index() function is prone to errors if the given input value does not exist in the given list. Further, you can improve it by doing little modification in the code and can be made error-free.

Using index() Method of List Class to Find Index Of An Item in A List

Index method in Python will simply return the index of the input value found in the list first. Hence if you have duplicate values then in that case you will get the index of the first occurrence of the value in the list.

Let us see in the below example code how it actually works and how you can modify it to make it error-free.

#Initializing the List
givenList = [10,11,12,13,14,15,12,13]

#get the Index of 12
getIndex = givenList.index(12)

#printing the index of Element 12
print("The Index of {} is {}".format(12,getIndex))

Output:

The Index of 12 is 2

As you can see from the above output, the index of 12 is only printed for its first occurrence at 2 and this method has ignored index 6.

But what if I need to search for the index of value 1 that is not present in the list in that case you will get ValueError: 1 is not in list. To fix this and if you still want to use the index method then you should use the below-modified index method.

def index(givenList, inputValue):
    #using Try and Catch to return values
    try:
        return givenList.index(inputValue)
    
    #If ValueError is found then Return None 
    except ValueError:
        return None

#Initializing the List
givenList = [10,11,12,13,14,15,12,13]

#get the Index of 1
getIndex = index(givenList, 1)

#printing the index of Element 1
print("The Index of {} is {}".format(1,getIndex))

Output:

The Index of 1 is None

As you can see in the above code, I have modified the index function to handle the ValueError and return None if the value is not found in the list.

Or you can simply modify the first code to handle the ValueError and then you are good to use it.

#Initializing the List
givenList = [10,11,12,13,14,15,12,13]

#get the Index of 1
try:
    getIndex = givenList.index(1)
except:
    getIndex = None

#printing the index of Element 1
print("The Index of {} is {}".format(1,getIndex))

Output:

The Index of 1 is None

Finding the Index of Value including to Duplicates

If you are looking to find the index of all the occurrences of the given values in Python then instead of using the index method you need to use enumerate method.

Using enumerate method you can iterate through the list and print out all the index values that match the input value or you can append the index to the list to later print the complete list of indexes of the given input value.

Let us see that in the example code below and how you can achieve finding all the occurrences of the value in the list.

#Initializing the List
givenList = [10,11,12,13,14,15,12,13]

#Value for which Index Required to be Found
valueOfWhichIndexIsRequired = 12

indexList = []

for index, value in enumerate(givenList):
    if value == valueOfWhichIndexIsRequired:
        #Saving the Index Values
        indexList.append(index)

#Printing all the index 
print("The index of {} is/are {}".format(valueOfWhichIndexIsRequired, indexList))

Output:

The index of 12 is/are [2, 6]
Finding The Index Of An Item In A List Python

Wrap Up

That is all for Finding the index of an item in a list[1]. I hope I was able to cover all aspects of the problem here. Note that using a try-except statement is really important and helps you ignore the extra loop through the list if you are using the index method.

Also, the index method is a linear run-time method, which means that it searches all the elements of the list. The time complexity can be understood as O(n) where n is the number of items in the list.

If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.

Further Read:

  1. How To Rewrite Python’s Max Function
  2. Python: How To Check If List Is Empty
  3. How To List All Files Of A Directory in Python
  4. How To Remove A Specific item From An Array
  5. How to Remove Last Element From List In Python
  6. Equivalent to “source” in OpenBSD? Python Linux/Unix

Leave a Comment