Check if Any item of List is Not in Another List in Python

This tutorial will discuss about a unique way to check if any element of a list is not in another list in Python.

Suppose we have two lists,

list1 = [11, 22, 33, 44, 55]
list2 = [67, 78, 49, 34, 19, 27]

We want to check if any element from first list list1 is not present in the second list list2.

First we will create two set objects from two lists. Then from the first set object we will call the difference() method and pass the second set object as argument. It will return as a new set containing elements which are present in first set, but are not present in the second set. Then we can compare the size of this new diff set and the set created from first list. Uf the returned set has elements less than the set created from the first list, then it means that at least one element from first list is present in the second list.

Whereas, if the size of the diff set is equal to the size of the first set, then it means that the no element from first list is present in the second list.

Let’s see the complete example,

# First List of numbers
list1 = [11, 22, 33, 44, 55]

# Second List of numbers
list2 = [67, 78, 49, 34, 19, 27]

# Check if both the lists have any common value
if len(set(list1).difference(set(list2))) < len(list1):
    print("At least one element from list1 is present in list2")
else:
    print("No element from list1 is present in list2")

Output

No element from list1 is present in list2

Summary

We learned how to check if any element of a List is present in another List in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top