skip to Main Content

Finding the index of an item in a list in python

In Python, you can find the index of an item in a list using the index() method or by iterating over the list manually. Here are examples of both approaches:

  1. Using the index() method:
my_list = ['apple', 'banana', 'orange', 'grape']
item = 'orange'

index = my_list.index(item)
print(index)  # Output: 2

In this example, the index() method is called on the list my_list with the item 'orange' as an argument. It returns the index of the first occurrence of the item in the list.

If the item is not found in the list, a ValueError is raised. To handle this, you can either use a try-except block to catch the exception or use the in operator to check if the item exists in the list before calling index().

  1. Iterating over the list manually:
my_list = ['apple', 'banana', 'orange', 'grape']
item = 'orange'

for index, value in enumerate(my_list):
    if value == item:
        print(index)  # Output: 2
        break

In this approach, the enumerate() function is used to iterate over the list along with the corresponding index. The loop checks if the current value matches the desired item, and if so, it prints the index and breaks out of the loop. This method allows you to find the index of an item without raising an exception if it is not found.

A Self Motivated Web Developer Who Loves To Play With Codes...

This Post Has 0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top