In this article, we will explore various methods to check if element exists inlist in Python. The simplest way to check for the presence of an element in a list is using thein Keyword.
Example:
Pythona=[10,20,30,40,50]# Check if 30 exists in the listif30ina:print("Element exists in the list")else:print("Element does not exist")
OutputElement exists in the list
Let's explore other different methods to check if element exists in list:
Using a loop
Usingfor loop we can iterate over each element in the list and check if an element exists. Using this method, we have an extra control during checking elements.
Pythona=[10,20,30,40,50]# Check if 30 exists in the list using a loopkey=30flag=Falseforvalina:ifval==key:flag=Truebreakifflag:print("Element exists in the list")else:print("Element does not exist")
OutputElement exists in the list
Note:This method is less efficient than using 'in'.
Using any()
The any()function is used to check if any element in an iterable evaluates toTrue. It returnsTrue if at least one element in the iterable is truthy (i.e., evaluates toTrue), otherwise it returnsFalse
Pythona=[10,20,30,40,50]# Check if 30 exists using any() functionflag=any(x==30forxina)ifflag:print("Element exists in the list")else:print("Element does not exist")
OutputElement exists in the list
Using count()
Thecount()function can also be used to check if an element exists by counting the occurrences of the element in the list. It is useful if we need to know the number of times an element appears.
Pythona=[10,20,30,40,50]# Check if 30 exists in the list using count()ifa.count(30)>0:print("Element exists in the list")else:print("Element does not exist")
OutputElement exists in the list
Which Method to Choose
- in Statement:The simplest and most efficient method for checking if an element exists in a list. Ideal for most cases.
- for Loop:Allows manual iteration and checking and provides more control but is less efficient than using 'in'.
- any():A concise option that works well when checking multiple conditions or performing comparisons directly on list.
- count(): Useful for finding how many times an element appears in the list but less efficient for checking existance of element only.
8 Methods to Check If an Element Exists in a List | Python Tutorial