Python Find in List: How to Find the Index of an Element in List

Here are four ways to find the index of an element in a Python List:

  1. Using list.index()
  2. Using for loop
  3. Using list comprehension 
  4. 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

Visual Representation How to Find the Index of an Element in List using list.index()

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 RepresentationVisual Representation of Use list comprehension with enumerate()

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

Visual Representation of Using filter() with lambda

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]

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.