Open In App

How to Find the Index for a Given Item in a Python List

Last Updated : 29 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We are given a list and our task is to find the index for a given item of a list in Python. In this article, we will explore each of the approaches along with their implementation.

Find the Index for a Given Item in a Python List

Below are the possible approaches to finding the index for a given item in a list in Python:

  • Using index() function
  • Using for Loop
  • Using List Comprehension with enumerate() function

Find the Index for a Given Item Using the index() function

In this example, we are using the index() function in Python, which returns the index of the first occurrence of the specified item in the list. The list lst contains integers from 10 to 50. We are searching for the item 30 within the list. The result res will be the index of 30 in the list, which is then printed out.

Python3
lst = [10, 20, 30, 40, 50]
item = 30
res = lst.index(item)
print(f"The index of {item} in the list is: {res}")

Output
The index of 30 in the list is: 2

Find the Index for a Given Item Using for Loop

In this example, we are using a for loop to iterate through the list lst. Within each iteration, we check if the current element is equal to the specified item (30 in this case). If a match is found, we assign the index i to the variable res and exit the loop using the break statement. Finally, we print the index of the item in the list using the variable res.

Python3
lst = [10, 20, 30, 40, 50]
item = 30
res = None
for i in range(len(lst)):
    if lst[i] == item:
        res = i
        break
print(f"The index of {item} in the list is: {res}")

Output
The index of 30 in the list is: 2

Find the Index for a Given Item Using List Comprehension with enumerate() function

In this example, we are using a list comprehension with the enumerate() function to iterate through the list lst and simultaneously track the index and value of each element. We filter the elements where the value matches the specified item (30 in this case) and store their indices in the list res. If res contains any indices, we print the index of the item in the list; otherwise, we print a message indicating that the item is not in the list.

Python3
lst = [10, 20, 30, 40, 50]
item = 30
res = [i for i, val in enumerate(lst) if val == item]
if res:
    print(f"The index of {item} in the list is: {res[0]}")
else:
    print(f"{item} is not in the list.")

Output
The index of 30 in the list is: 2

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads