To find the index of an item in a Python list, you can use the list.index()
method or iterate with enumerate()
. Here’s how to do it in different scenarios:
1. Using list.index()
(First Occurrence)
my_list = ["apple", "banana", "cherry", "banana"]
# Find the first occurrence of "banana"
index = my_list.index("banana")
print(index) # Output: 1
Key Notes:
- Raises a
ValueError
if the item is not found. - Use
in
to check existence first:
if "banana" in my_list:
index = my_list.index("banana")
2. Get All Indices of an Item (Multiple Occurrences)
Use enumerate()
in a list comprehension:
my_list = ["apple", "banana", "cherry", "banana"]
# Find all indices of "banana"
indices = [i for i, x in enumerate(my_list) if x == "banana"]
print(indices) # Output: [1, 3]
3. Handle Missing Items Gracefully
Wrap in a try-except
block to avoid ValueError
:
try:
index = my_list.index("mango")
except ValueError:
print("Item not found.")
4. Custom Function (Return -1
for Missing Items)
def find_index(lst, item):
try:
return lst.index(item)
except ValueError:
return -1
print(find_index(my_list, "mango")) # Output: -1
5. Search with a Starting Point
Find the next occurrence after a specific index:
# Find "banana" starting from index 2
index = my_list.index("banana", 2)
print(index) # Output: 3
When to Use Which Method
Method | Use Case |
---|---|
list.index() | Quick lookup for the first occurrence (error if not found). |
enumerate() + loop | Find all indices or handle complex conditions. |
try-except | Safely handle missing items. |
Example Workflow
# Example list
fruits = ["apple", "banana", "cherry", "banana"]
# Find first occurrence
print(fruits.index("banana")) # 1
# Find all occurrences
print([i for i, x in enumerate(fruits) if x == "banana"]) # [1, 3]
# Handle missing item
try:
print(fruits.index("mango"))
except ValueError:
print("Not in list") # "Not in list"
Let me know if you need more specific examples!