How to find the index of an object available in a list in Python?


In this article, we will show you how to find the index of an object in a given input list using python. Below are the 3 different methods to accomplish this task −

  • Using index() method

  • Using For Loop

  • Using List comprehension and enumerate() Function

Assume we have taken a list containing some elements. We will return the index of a specified object in a given input list.

Method 1: Using index() method

The index() function in Python allows you to find the index position of an element or item within a string of characters or a list of items. It returns the list's lowest possible index for the provided entry. A ValueError is returned if the specified item does not exist in the list

lst.index(item, start, end)

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Create a variable to store the input list

  • Use the index() function() to get the index of any element from the list by passing the list item/element as an argument to the index() function.

  • Print the index of the specified item from the list.

Example

The following program returns the index of the specified element in a list using the index() function −

lst = ["Python", "TutorialsPoint", "Hello", "TutorialsPoint", "Everyone"] # Printing the index of TutorialsPoint print("The index of 'TutorialsPoint' = ", lst.index("TutorialsPoint"))

Output

On executing, the above program will generate the following output −

The index of 'TutorialsPoint' = 1

ValueError is returned by the index() method if the specified item does not exist in the list as shown in the below code −

Example

In the below code “Java” is not present in the input list. So, when we try to print the index of Java, a ValueError is returned by the index() method. 

lst = ["Python", "TutorialsPoint", "Hello", "TutorialsPoint", "Everyone"] # Printing the index of Java # Now we get an error since Java is not in a list print("The index of 'Java' = ", lst.index("Java"))

Output

Traceback (most recent call last):
  File "main.py", line 4, in 
    print("The index of 'Java' = ", lst.index("Java"))
ValueError: 'Java' is not in list

Handling the Value Error

The following code handles the ValueError is returned by the index() method using the try-except blocks −

Here the except block statements will get executed if any error occurs.

Example

lst = ["Python", "TutorialsPoint", "Hello", "TutorialsPoint", "Everyone"] # Handling ValueError using try-except blocks try: print(lst.index("Java")) except ValueError: print("The element does not exist in the list")

Output

The element does not exist in the list

Method 2: Using For Loop

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Create a variable to store the input list.

  • Create a variable to store all the indices of any given list element(here TutorialsPoint).

  • Use the for loop, to traverse till the length of the list using the len() function( The number of items in an object is returned by the len() method).

  • Use the if conditional statement, to check whether the element present at the iterator index is equal to the "TutorialsPoint".

  • If the condition is true then add the corresponding index to the above newly created index list using the append() function(adds the element to the list at the end), if the condition is true.

  • Print all the indices of the 'TutorialsPoint'.

Example

The following program returns the index of the specified element in a list using the for loop and append() function −

# input list lst = ["TutorialsPoint", "Python", "TutorialsPoint", "Hello", "TutorialsPoint", "Everyone"] # Storing the indices of any given list element index_list = [] # Traversing till the length of the list for index in range(len(lst)): # Checking whether the element present at the iterator index is # equal to the "TutorialsPoint" if lst[index] == "TutorialsPoint": # Appending corresponding index to the index list if the condition is true index_list.append(index) # Printing all the indices of the 'TutorialsPoint' print("All indices of 'TutorialsPoint': ") print(index_list)

Output

All indices of 'TutorialsPoint':
[0, 2, 4]

Method 3: Using List comprehension and enumerate() Function

The enumerate() method adds a counter to an iterable and returns the enumerate object.

Syntax

enumerate(iterable, start=0)

Parameters

iterable − It can be any sequence/object/iterable supporting iteration

start − enumerate() begins counting from this value. If the start is not specified, the value 0 is used.

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Create a variable to store the input list and add some dummy data to it.

  • Using the enumerate() function use both the list index and list element as iterators and traverse the list.

  • Check if the list element is equal to the given object(“TutorialsPoint”) and if it is true then store only the index using list comprehension

  • Print all the indices of the 'TutorialsPoint'.

Example

The following program returns the index of the specified element in a list using the list comprehension and enumerate() function −

# input list lst = ["TutorialsPoint", "Python", "TutorialsPoint", "Hello", "TutorialsPoint", "Everyone"] # Storing all the indices of “TutorialsPoint” Here We are traversing the list using the enumerate function.enumerate() function has two iterators,lst_index refers to the index iterator and element refers to the list element iterator and checks whether the list element is equal to “TutorialsPoint”. index_list = [lst_indx for (lst_indx, element) in enumerate(lst) if element == "TutorialsPoint"] print("All indices of 'TutorialsPoint': ") print(index_list)

Output

All indices of 'TutorialsPoint':
[0, 2, 4]

Conclusion

In this article, we learned how to use the index() method to get the index of an element or object in a list, as well as how to utilize try-except blocks to handle the case where the element is not in the list. We learned how to use the enumerate() function to traverse through a list with two iterators.

Updated on: 22-Sep-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements