How to check if an element is in a List in Python
In this article, we will see how to check if an element is in a list in Python.
Method 1: Naive method
Here using the for loop we are iterating through all the elements to check the existence of the target element.
li = [4, 12, 5, 8, 1, 9] target = 5 for i in li: if i == target: print("exists")
Method 2: Using
This is the conventional method to check if an element is present in a list. It returns True if it exists, else False.
li = [4, 12, 5, 8, 1, 9] target = 5 if target in li: print("Element exists")
Please login to comment
View all comments