- 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 a list contains all the elements of another list
- Check if list1 contains all elements of list2 using all()
- Check if list1 contains any elements of list2 using any()
- Frequently Asked:
- Related posts:
- Share your love
- Leave a Comment Cancel Reply
- Terms of Use
- Disclaimer
- Check if Python List Contains All Elements of Another List
- Check if Python List Contains Elements of Another List
- all() method
- any() method
- Custom Search
- set() method
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 a list contains all the elements of another list
In this article we will discuss if a list contains all or any elements of another list.
Suppose we have have two list i.e.
# List of string list1 = ['Hi' , 'hello', 'at', 'this', 'there', 'from'] # List of string list2 = ['there' , 'hello', 'Hi']
Check if list1 contains all elements of list2 using all()
''' check if list1 contains all elements in list2 ''' result = all(elem in list1 for elem in list2) if result: print("Yes, list1 contains all elements in list2") else : print("No, list1 does not contains all elements in list2"
Python all() function checks if all Elements of given Iterable is True. So, convert the list2 to Iterable and for each element in Iterable i.e. list2 check if element exists in list1.
Check if list1 contains any elements of list2 using any()
''' check if list1 contains any elements of list2 ''' result = any(elem in list1 for elem in list2) if result: print("Yes, list1 contains any elements of list2") else : print("No, list1 contains any elements of list2")
Python any() function checks if any Element of given Iterable is True. So, convert the list2 to Iterable and for each element in Iterable i.e. list2 check if any element exists in list1.
Frequently Asked:
Complete example is as follows,
def main(): # List of string list1 = ['Hi' , 'hello', 'at', 'this', 'there', 'from'] # List of string list2 = ['there' , 'hello', 'Hi'] ''' check if list1 contains all elements in list2 ''' result = all(elem in list1 for elem in list2) if result: print("Yes, list1 contains all elements in list2") else : print("No, list1 does not contains all elements in list2") ''' check if list1 contains any elements of list2 ''' result = any(elem in list1 for elem in list2) if result: print("Yes, list1 contains any elements of list2") else : print("No, list1 contains any elements of list2") if __name__ == '__main__': main()
Yes, list1 contains all elements in list2 Yes, list1 contains any elements of list2
Related posts:
Share your love
Leave a Comment Cancel Reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Terms of Use
Disclaimer
Copyright © 2023 thisPointer
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Check if Python List Contains All Elements of Another List
In this sample program, you will learn to check if a Python list contains all the elements of another list and show the result using the print() function.
To understand this demo program, you should have basic Python programming knowledge.
Check if Python List Contains Elements of Another List
In the sample below, we are using two lists having overlapping values. One of these is the big one which holds all the elements of the second one.
- List1 – This list contains all or some of the elements of another.
- List2 – It is a subset of the first one.
Now, we’ve to programmatically prove that List1 contains the elements of List2. There could be multiple ways to achieve it.
all() method
To demonstrate that List1 has List2 elements, we’ll use the all() method.
# Program to check the list contains elements of another list # List1 List1 = [‘python’ , ‘javascript’, ‘csharp’, ‘go’, ‘c’, ‘c++’] # List2 List2 = [‘csharp1’ , ‘go’, ‘python’] check = all(item in List1 for item in List2) if check is True: print(«The list <> contains all elements of the list <>«.format(List1, List2)) else : print(«No, List1 doesn’t have all elements of the List2.»)
The output of the above code is as follows:
The list ['python', 'javascript', 'csharp', 'go', 'c', 'c++'] contains all elements of the list ['csharp', 'go', 'python']
any() method
Another method is any() which we can use to check if the list contains any elements of another one.
# Program to check the list contains elements of another list # List1 List1 = ['python' , 'javascript', 'csharp', 'go', 'c', 'c++'] # List2 List2 = ['swift' , 'php', 'python'] check = any(item in List1 for item in List2) if check is True: print("The list <> contains some elements of the list <>".format(List1, List2)) else : print("No, List1 doesn't have any elements of the List2.")
The output of the above code is as follows:
The list [‘python’, ‘javascript’, ‘csharp’, ‘go’, ‘c’, ‘c++’] contains some elements of the list [‘swift’, ‘php’, ‘python’]
Custom Search
In this method, we’ll write a custom search method to test if the first list contains the second one. While iterating the lists if we get an overlapping element, then the function returns true. The search continues until there is no element to match and returns false.
# Program to check if a Python list contains elements of another list def list_contains(List1, List2): check = False # Iterate in the 1st list for m in List1: # Iterate in the 2nd list for n in List2: # if there is a match if m == n: check = True return check return check # Test Case 1 List1 = ['a', 'e', 'i', 'o', 'u'] List2 = ['x', 'y', 'z', 'l', 'm'] print("Test Case#1 ", list_contains(List1, List2)) # Test Case 2 List1 = ['a', 'e', 'i', 'o', 'u'] List2 = ['a', 'b', 'c', 'd', 'e'] print("Test Case#2 ", list_contains(List1, List2))
The output of the above code is as follows:
Test Case#1 False Test Case#2 True
set() method
We’ll use the set() method to convert the lists and call Python set intersection() method to find if there is any match between the list elements.
# Program to check if a Python list contains elements of another list def list_contains(List1, List2): set1 = set(List1) set2 = set(List2) if set1.intersection(set2): return True else: return False # Test Case 1 List1 = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’] List2 = [‘x’, ‘y’, ‘z’, ‘l’, ‘m’] print(«Test Case#1 «, list_contains(List1, List2)) # Test Case 2 List1 = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’] List2 = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’] print(«Test Case#2 «, list_contains(List1, List2))
The output of the above code is as follows:
Test Case#1 False Test Case#2 True