W3docs

Python: Find in list

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

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

Find an element in a list in Python using the in keyword

# 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.")

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

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.

Find an element in a list in Python using the index method

# 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

Find an element in a list in Python using list comprehension

# 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)