Compare Two Lists & Find Missing Values in Python

This tutorial will discuss about unique ways to compare two lists & find missing values in Python.

Table Of Contents

Suppose we have two lists,

listObj1 = [32, 90, 78, 91, 17, 32, 22, 89, 22, 91]
listObj2 = [91, 89, 90, 91, 11]

We want to check if all the elements of first list i.e. listObj1 are present in the second list i.e. listObj2 or not. If not, then what are the missing values.

Find missing values between two Lists using Set

We want to find the missing values, basically the values which are present in first list listObj1, but not present in the second list listObj2. We can do that using 2 techniques . In the first one, we will create two Sets. One from the first list and second from the second list. Then we will take a difference between 2 sets. It will give us the missing values i.e. the values which are present in first list but not in second list.

Let’s see the complete example,

listObj1 = [32, 90, 78, 91, 17, 32, 22, 89, 22, 91]
listObj2 = [91, 89, 90, 91, 11]

# Get values which are in List listObj1 but not in List listObj2
missingValues = set(listObj1) - set(listObj2)

print(f'The missing values of listObj1 are: {missingValues}')

Output

The missing values of listObj1 are: {32, 17, 78, 22}

Find missing values between two Lists using For-Loop

Now instead of using a Set we can use a for loop. We will iterate over all the elements of the first list using for loop, and for each element we will check, if it is present in the second list or not. If not then we will add it into a new list i.e. a List of Missing Values. When the for loop ends, we will have new list containing the missing values i.e. the values which are present in first place but are not present in the second list.

Let’s see the complete example,

listObj1 = [32, 90, 78, 91, 17, 32, 22, 89, 22, 91]
listObj2 = [91, 89, 90, 91, 11]

# List to store missing values
missingValues = []

# Iterate over all elements of first list listObj1
# for each item check if it exists in second list listObj2
for item in listObj1:
    if item not in listObj2:
        missingValues.append(item)

print(f'The missing elements in list1 are: {missingValues}')

Output

The missing elements in list1 are: [32, 78, 17, 32, 22, 22]

Summary

We learned about two ways to find the missing elements in two lists 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