Python: Find in list

Here is a code snippet that demonstrates how to find an element in a list in Python:

# Define the list
my_list = [1, 2, 3, 4, 5]

# Define the element to search for
search_element = 3

# Use the 'in' keyword to check if the element is in the list
if search_element in my_list:
    print(f"{search_element} is in the list.")
else:
    print(f"{search_element} is not in the list.")

Watch a course Python - The Practical Guide

Alternatively, you can use the index() method to find the index of an element in a list, but it will raise ValueError if the element is not in the list.

# Define the list
my_list = [1, 2, 3, 4, 5]

# Define the element to search for
search_element = 3

try:
    index = my_list.index(search_element)
    print(f"{search_element} is at index {index} in the list.")
except ValueError:
    print(f"{search_element} is not in the list.")

You also have other alternatives like using list comprehension or filter to find items in list

# Using List Comprehension
search_element = 3
print([i for i in my_list if i == search_element])

# Using filter
result = list(filter(lambda x: x == search_element, my_list))
print(result)