Here are four ways to find the index of an element in a Python List:
- Using list.index()
- Using for loop
- Using list comprehension
- Using filter() with lambda
Method 1: Using list.index()
The index() function returns the index of the element’s first occurrence, regardless of whether the element appears twice.
Visual Representation
The above figure shows that we want to find the index of element 19. In the list, indexing starts with 0, so it appears that element 19 is located at index 2.
Example
main_list = [11, 21, 19, 46]
element_to_find = 19
try:
index = main_list.index(19)
print(f"{element_to_find} found at index {index}")
except ValueError:
print(f"{element_to_find} not found in the list")
Output
19 found at index 2
Method 2: Using for loop
We can use a for loop with the enumerate() function to search through a list for a specific element and provide its index if it is found.
Example
main_list = [11, 21, 19, 46]
# Element to find
element_to_find = 19
# Iterate through the list with a for loop
for index, element in enumerate(main_list):
if element == element_to_find:
print(f"{element_to_find} found at index {index}")
break # Stop the loop after finding the first occurrence
else:
print(f"{element_to_find} not found in the list")
Output
19 found at index 2
Method 3: Using list comprehension
If the same element appears multiple times in the list and you want to find the index of multiple occurrences, you can use list comprehension.
Visual Representation
The above figure shows that we have to find the index of element 19 in the list. As we can see, element 19 is located twice in the list, index 2 and index 4, so it returns 2 and 4.
Example
main_list = [11, 21, 19, 46, 19]
# Element to find
element_to_find = 19
# Use list comprehension with enumerate() to find indices
indices = [index for index, item in enumerate(main_list) if item == element_to_find]
if indices:
print(f"{element_to_find} found at indices {indices}")
else:
print(f"{element_to_find} not found in the list")
Output
19 found at indices [2, 4]
Method 4: Using filter() with lambda
Visual Representation
Example
main_list = [11, 21, 19, 46, 19]
# Element to find
element_to_find = 19
indices = list(filter(lambda x: main_list[x] == element_to_find, range(len(main_list))))
print(f"{element_to_find} found at indices {indices}")
Output
19 found at indices [2, 4]
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.