- Python List Contains: How to Check If Item Exists in List
- Method 1: Using the “in” operator
- Checking if the item exists in the list
- Syntax
- Return Value
- Example
- Method 2: Using List comprehension
- Example
- Method 3: Using the list.count() function
- Syntax
- Example
- Method 4: Using any() method
- Example
- Method 5: Use not in inverse operator.
- Example
- Conclusion
- Python: Check if Array/List Contains Element/Value
- Check if List Contains Element With for Loop
- Check if List Contains Element With in Operator
- Check if List Contains Element With not in Operator
- Check if List Contains Element With Lambda
- Free eBook: Git Essentials
- Check if List Contains Element Using any()
- Check if List Contains Element Using count()
- Conclusion
- Python : How to check if list contains value
- Check if value exist in List using ‘in’ operator
- Check if value exist in list using list.count() function
Python List Contains: How to Check If Item Exists in List
Here are the methods to check if a list contains an element in Python.
- Using the “in” operator
- Using “list comprehension”
- Using a “list.count()” method
- Using “any()” function
- Using the “not in” operator
Method 1: Using the “in” operator
To check if the list contains an element in Python, use the “in” operator. The “in” operator checks whether the list contains a specific item. It can also check if the element exists on the list using the list.count() function.
This approach returns True if an item exists in the list and False if an item does not exist. The list need not be sorted to practice this approach of checking.
Checking if the item exists in the list
To check if an item exists in the list, use the “in operator”. Then, use the “in” operator with the if condition, and if the item exists in the list, then the condition returns True, and if not, it returns False.
Syntax
Return Value
It will return True if an item exists in the list else returns False.
Example
listA = ['Stranger Things', 'S Education', 'Game of Thrones'] if 'S Eductation' in listA: print("'S Eductation' found in List : ", listA)
'S Eductation' found in List : ['Stranger Things', 'S Education', 'Game of Thrones']
Let’s take an example where we do not find an item on the list.
listA = ['Stranger Things', 'S Education', 'Game of Thrones'] if 'Dark' in listA: print("Yes, 'S Eductation' found in List : ", listA) else: print("Nope, 'Dark' not found in the list")
Nope, 'Dark' Not found in the list
The list does not contain the dark element, so it returns False, and the else block executes.
Method 2: Using List comprehension
Use a list comprehension to check if a list contains single or multiple elements in Python.
Example
main_list = [11, 21, 19, 18, 46] check_elements = [11, 19, 46] if all([item in main_list for item in check_elements]): print("The list contains all the items")
The list contains all the items
In this example, we defined two lists.
- The main_list is our primary list which we will check for multiple elements.
- The check_elements list contains elements we will check in the main_list.
Using list comprehension, we check if all the elements of check_list are present in the main_list.
In our case, It returns True since all the elements are present. That’s why if condition is executed.
Method 3: Using the list.count() function
To check if the item exists in the Python list, use the list.count() method.
Syntax
The List count(item) method returns the occurrence count of the given element. If it’s greater than 0, a given item exists in the list.
Example
listA = ['Stranger Things', 'S Education', 'Game of Thrones'] if listA.count('Stranger Things') > 0: print("'Stranger Things' found in List : ", listA)
'Stranger Things' found in List : ['Stranger Things', 'S Education', 'Game of Thrones']
Method 4: Using any() method
Python any() function is the most classical way to perform this task efficiently. The any() function checks for a match in a string with a match of each list element.
Example
data_string = "The last season of Game of Thrones was not good" listA = ['Stranger Things', 'S Education', 'Game of Thrones'] print("The original string : " + data_string) print("The original list : " + str(listA)) res = any(item in data_string for item in listA) print("Does string contain 'Game of Thrones' list element: " + str(res))
The original string : The last season of Game of Thrones was not good The original list : ['Stranger Things', 'S Education', 'Game of Thrones'] Does string contain 'Game of Thrones' list element: True
From the output, Game of Thrones exists in the list.
Method 5: Use not in inverse operator.
Python “not in” is a built-in operator that evaluates to True if it does not find a variable in the specified sequence and False otherwise.
To check if the list contains a particular item, you can use the “not in” inverse operator.
Example
listA = ['Stranger Things', 'S Education', 'Game of Thrones'] if 'Witcher' not in listA: print("'Witcher' is not found in List : ", listA)
'Witcher' is not found in List : ['Stranger Things', 'S Education', 'Game of Thrones']
Python in and not in operators work fine for lists, tuples, sets, and dicts (check keys).
Conclusion
The best and most efficient way to check if a list contains an element is to use the “in operator” in Python.
Python: Check if Array/List Contains Element/Value
In this tutorial, we’ll take a look at how to check if a list contains an element or value in Python. We’ll use a list of strings, containing a few animals:
animals = ['Dog', 'Cat', 'Bird', 'Fish']
Check if List Contains Element With for Loop
A simple and rudimentary method to check if a list contains an element is looping through it, and checking if the item we’re on matches the one we’re looking for. Let’s use a for loop for this:
for animal in animals: if animal == 'Bird': print('Chirp!')
Check if List Contains Element With in Operator
Now, a more succinct approach would be to use the built-in in operator, but with the if statement instead of the for statement. When paired with if , it returns True if an element exists in a sequence or not. The syntax of the in operator looks like this:
Making use of this operator, we can shorten our previous code into a single statement:
if 'Bird' in animals: print('Chirp')
This code fragment will output the following:
This approach has the same efficiency as the for loop, since the in operator, used like this, calls the list.__contains__ function, which inherently loops through the list — though, it’s much more readable.
Check if List Contains Element With not in Operator
By contrast, we can use the not in operator, which is the logical opposite of the in operator. It returns True if the element is not present in a sequence.
Let’s rewrite the previous code example to utilize the not in operator:
if 'Bird' not in animals: print('Chirp')
Running this code won’t produce anything, since the Bird is present in our list.
But if we try it out with a Wolf :
if 'Wolf' not in animals: print('Howl')
Check if List Contains Element With Lambda
Another way you can check if an element is present is to filter out everything other than that element, just like sifting through sand and checking if there are any shells left in the end. The built-in filter() method accepts a lambda function and a list as its arguments. We can use a lambda function here to check for our ‘Bird’ string in the animals list.
Then, we wrap the results in a list() since the filter() method returns a filter object, not the results. If we pack the filter object in a list, it’ll contain the elements left after filtering:
retrieved_elements = list(filter(lambda x: 'Bird' in x, animals)) print(retrieved_elements)
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Now, this approach isn’t the most efficient. It’s fairly slower than the previous three approaches we’ve used. The filter() method itself is equivalent to the generator function:
(item for item in iterable if function(item))
The slowed down performance of this code, amongst other things, comes from the fact that we’re converting the results into a list in the end, as well as executing a function on the item on each iteration.
Check if List Contains Element Using any()
Another great built-in approach is to use the any() function, which is just a helper function that checks if there are any (at least 1) instances of an element in a list. It returns True or False based on the presence or lack thereof of an element:
if any(element in 'Bird' for element in animals): print('Chirp')
Since this results in True , our print() statement is called:
This approach is also an efficient way to check for the presence of an element. It’s as efficient as the first three.
Check if List Contains Element Using count()
Finally, we can use the count() function to check if an element is present or not:
This function returns the occurrence of the given element in a sequence. If it’s greater than 0, we can be assured a given item is in the list.
Let’s check the results of the count() function:
if animals.count('Bird') > 0: print("Chirp")
The count() function inherently loops the list to check for the number of occurrences, and this code results in:
Conclusion
In this tutorial, we’ve gone over several ways to check if an element is present in a list or not. We’ve used the for loop, in and not in operators, as well as the filter() , any() and count() methods.
Python : How to check if list contains value
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.
# List ourlist= ['list' , 'of', 'different', 'strings', 'to', 'find','to']
Check if value exist in List using ‘in’ operator
Format to use ‘in’ operator:
Above is conditional expression which will return boolean value : True or False.
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() function gives the number of occurrences of the value passed as parameter.
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.