
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python program to find missing and additional values in two lists?
In this article, we will explore how to find missing and additional values in two lists. This type of comparison is can be encountered in the real-world scenarios such as data validation or system synchronization.
The task is to determine which elements are missing in one list and what unexpected elements were received. This can be achieved by using the python built-in data structures like sets that allows for easy comparison.
Using set() Function
The python set() function is used to used to create a new set. A set is a collection of unique elements (each ite, appears only once in the set).
Syntax
Following is the syntax of Python set() function -
set(iterable)
Using set.difference() Method
The python set.difference() method is used to return the new set containing the elements that are present in the first set but not in any other sets provided as arguments.
Syntax
Following is the syntax of Python set.difference() method -
set.difference(*others)
Here we are going to consider the two lists and convert them into sets using the set() function and then applying the set.difference() method, In this scenario, we are going to apply this method in two cases.
- For finding the missing values, we are passing second set as a argument to the difference() method.
- For finding the additional values, we are passing the first set as a argument to the difference() method.
Example 1
Let's look at the following example, where we are going to compare trhe two list to find missing and additional values.
def demo(x, y): set1 = set(x) set2 = set(y) a = set1.difference(set2) b = set2.difference(set1) return list(a), list(b) x = [11,2,33,22,44] y = [44,2,11,33,55] a, b = demo(x, y) print("Missing:", a) print("Additional:", b)
The output of the above program is as follows -
Missing: [22] Additional: [55]
Example 2
In the following example, we are going to consider the list with duplicate values and finding the missing and additional values.
def demo(x, y): set1 = set(x) set2 = set(y) a = set1.difference(set2) b = set2.difference(set1) return list(a), list(b) x = [22,1,22,1,3] y = [22,1,4] a, b = demo(x, y) print("Missing:", a) print("Additional:", b)
The following is the output of the above program -
Missing: [3] Additional: [4]