Python check if list contains elements of another list
In this post, you will learn how to check if a list contains elements of another list using the Python programming language.
A list is a sequence of indexed and ordered values, like an array. It is mutable, which means we can change the order of elements in a list. It contains a list of any type of data object with a comma separated and enclosed within a square bracket. In the development process, we may come to a situation in which we need to check if a list contains elements of another list. Here, we have mentioned different ways to achieve this task.
Check if list contains elements of another list using any() function
The any() function is an inbuilt function in Python which returns true if any of the elements of a given iterable are True, else it returns False. In the given example, we have taken two variables, list_x and list_y, and checked if a list contains any item from another list.
## checking any element of list_x in list_y
list_x = [11, 31, 12, 51]
list_y = [51, 12, 31]
check = any(item in list_x for item in list_y)
print(check)
Output of the above code:
True
Check if list contains elements of another list using all() function
The all() function of Python returns True if all elements in the given iterable are true. If not, it returns False. In the given example, we have taken two variables, list_x and list_y, and checked if all elements exist in another list. If satisfied, it returns True else it returns False.
## checking any elment of list_x in list_y
list_x = [10, 12, 32, 25]
list_y = [10, 32, 25]
check = all(item in list_x for item in list_y)
print(check)
Output of the above code:
True
Check if list contains elements of another list using intersection method
In the given example, we have used the Python set intersection() method to find if there is any match between the two given list elements.
## checking any elment of list_x in list_y
list_x = [1, 2, 3, 4]
list_y = [2, 3]
set_x = set(list_x)
set_y = set(list_y)
print(set_x.intersection(set_y))
Output of the above code:
{21, 30}
Related Articles
Python convert list to numpy array
How to shuffle a list in Python
Print hollow diamond pattern in Python
Python *args **kwargs
Write a python program to sum all the numbers in a list
Shuffle list python
Convert array to list Python
Remove element from list Python
Convert list to dictionary Python
Python dict inside list
Convert list to string Python
Remove last element from list Python
Convert string to list Python
Python add list to list
Difference between tuple and list in Python
Alphabetical order Python
Python | Generate QR Code using pyqrcode module