0
0
PythonHow-ToBeginner · 3 min read

How to Check if Element Exists in List in Python

To check if an element exists in a list in Python, use the in keyword like element in list. It returns True if the element is found, otherwise False.
📐

Syntax

The syntax to check if an element exists in a list uses the in keyword.

  • element: The item you want to find.
  • list: The list you want to search in.
  • The expression element in list returns True if the element is in the list, otherwise False.
python
element in list
💻

Example

This example shows how to check if the number 3 is in a list of numbers and prints the result.

python
numbers = [1, 2, 3, 4, 5]
if 3 in numbers:
    print("3 is in the list")
else:
    print("3 is not in the list")
Output
3 is in the list
⚠️

Common Pitfalls

Some common mistakes include:

  • Using == to compare the whole list instead of checking membership.
  • Checking for an element with wrong data type (e.g., string vs integer).
  • Assuming in works for nested lists without extra steps.
python
numbers = [1, 2, 3]

# Wrong: compares whole list, not membership
print(3 == numbers)  # False

# Right: check membership
print(3 in numbers)  # True
Output
False True
📊

Quick Reference

Tips for checking element existence in lists:

  • Use in for simple membership tests.
  • Use not in to check if element is absent.
  • Remember that in works with any iterable, not just lists.

Key Takeaways

Use the in keyword to check if an element exists in a list.
element in list returns True if found, otherwise False.
Avoid comparing the element with the whole list using ==.
Check data types carefully to avoid false negatives.
Use not in to check if an element is not in the list.