This tutorial will discuss about a unique way to check if any element in list is in another list in Python.
Suppose we have two lists,
list1 = [11, 22, 33, 44, 55] list2 = [67, 78, 44, 34, 19, 27]
We want to check if any element from the first list list1 is present in the second list list2 or not.
For this, we will create two set objects i.e. first set from the first list and second set from the second list. Then we can call the intersection()
method on the first set object and pass the second set as an argument in this method. It will return a new set containing the elements which are present in both the sets i.e. the elements which are present in both the lists list1 & list2.
If the new Set is empty, then it means both the lists has no common element. Where, if Set is non empty, then it means it contains the values from list1 which are pesent in list2.
Let’s see the complete example,
# First List of numbers list1 = [11, 22, 33, 44, 55] # Second List of numbers list2 = [67, 78, 44, 34, 19, 27] # Check if two lists have any common element if set(list1).intersection(set(list2)): print("Yes, At least one element from list1 is present in list2") else: print("No element from list1 is present in list2")
Output
Frequently Asked:
Yes, At least one element from list1 is present in list2
Summary
We learned how to check if any element in list is in another list in Python.