How to Find Index of Element in List in Python
Use the
list.index(element) method to find the first position of an element in a list. It returns the index as an integer, starting from 0, or raises a ValueError if the element is not found.Syntax
The syntax to find the index of an element in a list is:
list.index(element): Returns the first index ofelementin the list.element: The value you want to find in the list.
If the element is not in the list, Python raises a ValueError.
python
index = my_list.index(element)
Example
This example shows how to find the index of an element in a list. It prints the index if found.
python
my_list = ['apple', 'banana', 'cherry', 'date'] index = my_list.index('cherry') print(f"The index of 'cherry' is: {index}")
Output
The index of 'cherry' is: 2
Common Pitfalls
Trying to find the index of an element not in the list causes a ValueError. To avoid this, check if the element exists first or use a try-except block.
python
my_list = [1, 2, 3] # Wrong way: raises ValueError if element not found # index = my_list.index(4) # Right way: check before searching if 4 in my_list: index = my_list.index(4) print(f"Index: {index}") else: print("Element not found") # Or use try-except try: index = my_list.index(4) print(f"Index: {index}") except ValueError: print("Element not found")
Output
Element not found
Element not found
Quick Reference
Summary tips for finding an element's index in a list:
- Use
list.index(element)to get the first occurrence index. - Indexing starts at 0.
- Handle
ValueErrorif element is missing. - Use
inkeyword to check presence before searching.
Key Takeaways
Use list.index(element) to find the first index of an element in a list.
If the element is not found, list.index() raises a ValueError.
Check if the element exists with 'in' before calling index() to avoid errors.
Index counting in Python lists starts at zero.
Use try-except to handle cases where the element might be missing.