Python : How to check if list contains value
By Parth Patel on Oct 04, 2018
In this quick code reference, I will demonstrate how to check whether value or item exists in python list or not. It is very easy to find if list contains a value with either in or not in operator.
Let's take an example -
We have a list below:
# List
ourlist= ['list' , 'of', 'different', 'strings', 'to', 'find','to']
Check if value exist in List using 'in' operator
Format to use 'in' operator:
{value} in [list]
Above is conditional expression which will return boolean value : True or False.
Let's try on our list:
if 'list' in ourlist:
print('"list" is found in ourlist')
You can also use negation operator to check if value does not exist in list. See example below:
if 'apple' not in ourlist:
print('"apple" is not found in ourlist')
The 'in' operator is by far easiest way to find if element exists in list or not but in python there are some other ways too to check whether list contains value or not.
Check if value exist in list using list.count() function
Format to use list.count() function in python:
list.count('value')
List.count() function gives the number of occurrences of the value passed as parameter.
Let's try on our list:
if ourlist.count('to') > 0:
print('"to" exists in ourlist');
Here, we used this function in if condition to determine if number of occurence is equal to 0 then the value does not exist in our list else value exist in our list.
There are other ways to check item exist in list or not but most of the cases, you won't need it. 'in' operator is the most helpful in such case.
Adios
Also read: