How to Check if an Item Exists in a List in Python
In this tutorial, we are going to see how to check if an item exists in a list in Python. In Python, a list is a container of items, used to store multiple data at the same time. Unlike Set, the list in Python is ordered and has a defined number. The elements of a list are indexed according to a defined sequence and the indexing of a list is done with 0 as the first index.
Knowledge of some operations on lists is necessary. This article describes one of the basic operations to check the existence of an element in the list.
How to Check if an item exists in a list in Python Using the “in” operator
The “in” operator is the easiest way to check whether or not an item exists in a list. The “in” operator returns “True” if the item exists in the list and “False” if the item does not exist in the list. The list does not need to be sorted to check it.
Example: Check if ‘StackHowTo’ exists in the list.
strList = ['welcome', 'to', 'StackHowTo'] if 'StackHowTo' in strList : print("True, 'StackHowTo' exists in the list : " , strList)
This produces the following output:
True, 'StackHowTo' exists in the list : ['welcome', 'to', 'StackHowTo']
Code to check if the item is not in the list:
strList = ['welcome', 'to', 'StackHowTo'] if 'Blue' not in strList : print("True, 'Blue' doesn't exists in the list : " , strList)
This produces the following output:
True, 'Blue' doesn't exists in the list : ['welcome', 'to', 'StackHowTo']
How to Check if an item exists in a list in Python Using count() method
count(element) function returns the number of occurrences of a given element in the list. If its value is greater than 0, it means that a given item exists in the list.
Example : Check if ‘StackHowTo’ exists in the list.
strList = ['Hi' , 'welcome', 'to', 'StackHowTo'] if strList.count('StackHowTo') > 0 : print("True, 'StackHowTo' exists in the list : " , strList)
This produces the following output:
True, 'StackHowTo' exists in the list : ['welcome', 'to', 'StackHowTo']