In Python, slicing is a technique used to extract a portion (or a subset) of…
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:
- Using the
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
- 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.