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 listreturnsTrueif the element is in the list, otherwiseFalse.
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
inworks 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
infor simple membership tests. - Use
not into check if element is absent. - Remember that
inworks 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.