Python list contains single or multiple items. While working with these list items we may need to check if the list contains a specified item or value. There are different operators in order to check if the list contains a specified item or value.
Check If Items Exist In List Using in Operator
The in
operator is used to checking if the specified item or value exists in the specified collection which can be a list. The in operator is used with the if statement and if the specified item or value exists in the specified list some statements can be executed inside the if statement body.
names=["ismail","ahmet","ali"]
if "ahmet" in names:
print("ahmet exist in the list")
Check If Items Exist In List Using not in Operator
The not in
operator is the reverse of the in
operator where it can be also used to check if the specified item or value exists in a list. We will use the else
statement if the element exists in the list.
names=["ismail","ahmet","ali"]
if "ahmet" not in names:
pass
else:
print("ahmet exist in the list")
Check If Items Exist In List Using List Comprehension
List comprehension can be also used to check the item or value that exists in a list. The result is saved as a boolean value as True
or False
.
names=["ismail","ahmet","ali"]
result = [i for i in names if(i in )]
Check If Items Exist In List Using in List Count Method
The List type provides count()
method order to count specified values in the list items. The number of occurrences of the item is returned and if it is 0 this means the item or values does not exist in the list. If the return value is 1 or more the item exists in the list.
names=["ismail","ahmet","ali"]
if names.count("ahmet")>0:
print("ahmet exist in the list")
Check If Multiple Items or List Exist In List Using in List All Method
In some cases, we may need to check multiple items or values that exist in a list. the all()
function can be used to check a list in a list. In the following example, we check if the list mynames
exists in the names
.
names=["ismail","ahmet","ali","elif","ecrin"]
mynames=["ismail"]
result = any(item in names for item in mynames)
print(result)
True