The Wayback Machine - http://web.archive.org/web/20240930171643/https://www.geeksforgeeks.org/python-find-missing-additional-values-two-lists/
Open In App

Python | Find missing and additional values in two lists

Last Updated : 13 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given two lists, find the missing and additional values in both the lists. Examples:

Input : list1 = [1, 2, 3, 4, 5, 6] 
        list2 = [4, 5, 6, 7, 8] 
Output : Missing values in list1 = [8, 7] 
         Additional values in list1 = [1, 2, 3] 
         Missing values in list2 = [1, 2, 3] 
         Additional values in list2 = [7, 8] 

Explanation: 
 

Approach: To find the missing elements of list2 we need to get the difference of list1 from list2. To find the additional elements of list2, calculate the difference of list2 from list1. Similarly while finding missing elements of list1, calculate the difference of list2 from list1. To find the additional elements in list1, calculate the difference of list1 from list2. Insert the list1 and list2 to set and then use difference function in sets to get the required answer. Prerequisite : Python Set Difference 

Python3




# Python program to find the missing
# and additional elements
 
# examples of lists
list1 = [1, 2, 3, 4, 5, 6]
list2 = [4, 5, 6, 7, 8]
 
# prints the missing and additional elements in list2
print("Missing values in second list:", (set(list1).difference(list2)))
print("Additional values in second list:", (set(list2).difference(list1)))
 
# prints the missing and additional elements in list1
print("Missing values in first list:", (set(list2).difference(list1)))
print("Additional values in first list:", (set(list1).difference(list2)))


Output:

Missing values in second list: {1, 2, 3}
Additional values in second list: {7, 8}
Missing values in first list: {7, 8}
Additional values in first list: {1, 2, 3}

Approach using numpy:

note: install numpy module using command “pip install numpy”

Algorithm:

Convert list1 and list2 to numpy arrays using numpy.array() function.
Calculate the missing values in list2 using numpy.setdiff1d() with arguments arr1 and arr2.
Calculate the additional values in list2 using numpy.setdiff1d() with arguments arr2 and arr1.
Calculate the missing values in list1 using numpy.setdiff1d() with arguments arr2 and arr1.
Calculate the additional values in list1 using numpy.setdiff1d() with arguments arr1 and arr2.
Convert the numpy arrays to lists using list() function and return the results.
 

Python3




import numpy as np
 
 
def find_missing_additional(list1, list2):
    # Convert list1 and list2 to numpy arrays
    arr1 = np.array(list1)
    arr2 = np.array(list2)
 
    # Calculate missing and additional values in list2
    missing_list2 = np.setdiff1d(arr1, arr2)
    additional_list2 = np.setdiff1d(arr2, arr1)
 
    # Calculate missing and additional values in list1
    missing_list1 = np.setdiff1d(arr2, arr1)
    additional_list1 = np.setdiff1d(arr1, arr2)
 
    # Convert numpy arrays to lists and return the results
    return list(missing_list2), list(additional_list2), list(missing_list1), list(additional_list1)
list1 = [1, 2, 3, 4, 5, 6]
list2 = [4, 5, 6, 7, 8]
 
missing_list2, additional_list2, missing_list1, additional_list1 = find_missing_additional(list1, list2)
print("Missing values in first list:", missing_list1)
print("Additional values in first list:", additional_list1)
print("Missing values in second list:", missing_list2)
print("Additional values in second list:", additional_list2)


Output:

Missing values in first list: [7, 8]
Additional values in first list: [1, 2, 3]
Missing values in second list: [1, 2, 3]
Additional values in second list: [7, 8]

Time complexity:
The time complexity of the numpy.setdiff1d() function is O(nlogn) since it involves sorting the arrays. Therefore, the time complexity of this algorithm is O(nlogn) where n is the length of the input lists.

Auxiliary Space:
The space complexity of this algorithm is O(n) where n is the length of the input lists, as we are creating numpy arrays of length n.



Similar Reads

How to Pass Additional Context into a Class Based View (Django)?
Passing context into your templates from class-based views is easy once you know what to look out for. There are two ways to do it - one involves get_context_data, the other is by modifying the extra_context variable. Let see how to use both the methods one by one. Explanation: Illustration of How to use get_context_data method and extra_context va
2 min read
Django REST Framework: Adding Additional Field to ModelSerializer
Django REST Framework (DRF) is a powerful and flexible toolkit for building Web APIs in Django. One of its key features is the ModelSerializer class, which provides a shortcut for creating serializers that deal with Django model instances and querysets. However, there are times when you may need to add additional fields to a ModelSerializer that ar
3 min read
Replacing missing values using Pandas in Python
Dataset is a collection of attributes and rows. Data set can have missing data that are represented by NA in Python and in this article, we are going to replace missing values in this article We consider this data set: Dataset In our data contains missing values in quantity, price, bought, forenoon and afternoon columns, So, We can replace missing
2 min read
How to handle missing values of categorical variables in Python?
Machine Learning is the field of study that gives computers the capability to learn without being explicitly programmed. Often we come across datasets in which some values are missing from the columns. This causes problems when we apply a machine learning model to the dataset. This increases the chances of error when we are training the machine lea
4 min read
How to deal with missing values in a Timeseries in Python?
It is common to come across missing values when working with real-world data. Time series data is different from traditional machine learning datasets because it is collected under varying conditions over time. As a result, different mechanisms can be responsible for missing records at different times. These mechanisms are known as missingness mech
10 min read
Drop rows from Pandas dataframe with missing values or NaN in columns
Pandas provides various data structures and operations for manipulating numerical data and time series. However, there can be cases where some data might be missing. In Pandas missing data is represented by two value: None: None is a Python singleton object that is often used for missing data in Python code. NaN: NaN (an acronym for Not a Number),
4 min read
Count NaN or missing values in Pandas DataFrame
In this article, we will see how to Count NaN or missing values in Pandas DataFrame using isnull() and sum() method of the DataFrame. Dataframe.isnull() method Pandas isnull() function detect missing values in the given object. It return a boolean same-sized object indicating if the values are NA. Missing values gets mapped to True and non-missing
5 min read
Imputing Missing Values Before Building an Estimator in Scikit Learn
The missing values in a dataset can cause problems during the building of an estimator. Scikit Learn provides different ways to handle missing data, which include imputing missing values. Imputing involves filling in missing data with estimated values that are based on other available data in the dataset. Related topic of concepts:Missing Data: Mis
3 min read
Python - Unique value keys in a dictionary with lists as values
Sometimes, while working with Python dictionaries, we can have problem in which we need to extract keys with values that are unique (there should be at least one item not present in other lists), i.e doesn't occur in any other key's value lists. This can have applications in data preprocessing. Lets discuss certain ways in which this task can be pe
4 min read
Creating a sorted merged list of two unsorted lists in Python
We need to take two lists in Python and merge them into one. Finally, we display the sorted list. Examples: Input : list1 = [25, 18, 9, 41, 26, 31] list2 = [25, 45, 3, 32, 15, 20] Output : [3, 9, 15, 18, 20, 25, 25, 26, 31, 32, 41, 45] Input : list1 = ["suraj", "anand", "gaurav", "aman", "kishore"] list2 = ["rohan", "ram", "mohan", "priya", "komal"
1 min read
Python | Union of two or more Lists
Union of a list means, we must take all the elements from list A and list B (there can be more than two lists) and put them inside a single new list. There are various orders in which we can combine the lists. For e.g., we can maintain the repetition and order or remove the repeated elements in the final list and so on. Examples: Maintained repetit
7 min read
Python | Check if two lists have at-least one element common
Given two lists a, b. Check if two lists have at least one element common in them. Examples: Input : a = [1, 2, 3, 4, 5] b = [5, 6, 7, 8, 9] Output : True Input : a=[1, 2, 3, 4, 5] b=[6, 7, 8, 9] Output : FalseMethod 1: Traversal of List Using traversal in two lists, we can check if there exists one common element at least in them. While traversing
5 min read
Python | Check whether two lists are circularly identical
Given two lists, check if they are circularly identical or not. Examples: Input : list1 = [10, 10, 0, 0, 10] list2 = [10, 10, 10, 0, 0] Output : Yes Explanation: yes they are circularly identical as when we write the list1 last index to second last index, then we find it is circularly same with list1 Input : list1 = [10, 10, 10, 0, 0] list2 = [1, 1
5 min read
Python | Print all the common elements of two lists
Given two lists, print all the common elements of two lists. Examples: Input : list1 = [1, 2, 3, 4, 5] list2 = [5, 6, 7, 8, 9] Output : {5} Explanation: The common element of the lists is 5. Input : list1 = [1, 2, 3, 4, 5] list2 = [6, 7, 8, 9] Output : No common elements Explanation: They do not have any elements in common in between them Method 1:
8 min read
Python | Check if two lists are identical
This article deals with the task of ways to check if two unordered list contains exact similar elements in exact similar position, i.e to check if two lists are exactly equal. This is quite a useful utility and can be used in day-day programming. Method 1: Using list.sort() and == operator sort() coupled with == operator can achieve this task. We f
7 min read
Python | Extract Combination Mapping in two lists
Sometimes, while working with Python lists, we can have a problem in which we have two lists and require to find the all possible mappings possible in all combinations. This can have possible application in mathematical problems. Let's discuss certain way in which this problem can be solved. Method : Using zip() + product() With these functions thi
2 min read
How to Concatenate Two Lists Index Wise in Python
Index-wise concatenation of two lists refers to adding or combining elements of the given list based on their indices. There are many real-world applications of concatenating two lists index-wise, such as data processing, string manipulation, generating composite keys or super keys(in the database), and so on. In this article, we are going to deep
4 min read
Merge Two Lists in Python
Let's see how to concatenate two lists using different methods in Python. This operation is useful when we have a number of lists of elements that need to be processed in a similar manner. Input: test_list1 = [1, 4, 5, 6, 5] test_list2 = [3, 5, 7, 2, 5]Output: [1, 4, 5, 6, 5, 3, 5, 7, 2, 5]Explanation: The output list is the list we get from Mergin
7 min read
Python | Difference between two lists
In Python programming, comparing two lists is a common task with multiple approaches. This article explores different methods for obtaining the dissimilarity between two lists, enhancing your proficiency in handling lists and data comparison in Python. Join us on this insightful journey into various strategies for discerning differences between lis
6 min read
Python | Intersection of two lists
Intersection of two list means we need to take all those elements which are common to both of the initial lists and store them into another list. Now there are various ways in Python, through which we can perform the Intersection of the lists. Examples: Input : lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]Output :[
6 min read
Python | Convert two lists into a dictionary
Interconversion between data types is usually necessary for real-time applications as certain systems have certain modules that require input in a particular data type. Let's discuss a simple yet useful utility of conversion of two lists into a key: value pair dictionary in Python. Converting Two Lists into a DictionaryPython List is a sequence dat
11 min read
Highlight the negative values red and positive values black in Pandas Dataframe
Let's see various methods to Highlight the positive values red and negative values black in Pandas Dataframe.First, Let's make a Dataframe: C/C++ Code # Import Required Libraries import pandas as pd import numpy as np # Create a dictionary for the dataframe dict = { 'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], '
3 min read
Mapping external values to dataframe values in Pandas
Mapping external values to a dataframe means using different sets of values to add to that dataframe by keeping the keys of the external dictionary as same as the one column of that dataframe. To add external values to dataframe, we use a dictionary that has keys and values which we want to add to the dataframe. By adding external values in the dat
3 min read
Sort a String in decreasing order of values associated after removal of values smaller than X
Given an integer X and a string str consisting of space-separated texts and numbers placed alternately, the task is to sort the string such that texts and numbers appear in decreasing order of numbers associated after removal of all numbers less than X. If two strings have the same values then sort them in the lexicographic order of the string. Exa
8 min read
Handling missing keys in Python dictionaries
In Python, dictionaries are containers that map one key to its value with access time complexity to be O(1). But in many applications, the user doesn't know all the keys present in the dictionaries. In such instances, if the user tries to access a missing key, an error is popped indicating missing keys. Handling Missing Keys in Python DictionariesI
4 min read
Fix: "SyntaxError: Missing Parentheses in Call to 'print'" in Python
In Python, if we see the "SyntaxError: Missing Parentheses in Call to 'print'" error, it means we forgot to use parentheses around what we want to print. This is the most common error that we encounter when transitioning from Python 2 to Python 3. This error occurs due to a significant change in how the print statement works between Python2 and Pyt
3 min read
Find common values between two NumPy arrays
In NumPy, we can find common values between two arrays with the help intersect1d(). It will take parameter two arrays and it will return an array in which all the common elements will appear. Syntax: numpy.intersect1d(array1,array2) Parameter :Two arrays. Return :An array in which all the common element will appear. Example 1: Python Code import nu
1 min read
Find common values between two NumPy arrays
In this article, we are going to discuss how to find out the common values between 2 arrays. To find the common values, we can use the numpy.intersect1d(), which will do the intersection operation and return the common values between the 2 arrays in sorted order. Syntax: numpy.intersect1d(arr1, arr2, assume_unique = False, return_indices = False) P
2 min read
Replace missing white spaces in a string with the least frequent character using Pandas
Let's create a program in python which will replace the white spaces in a string with the character that occurs in the string very least using the Pandas library. Example 1: String S = "akash loves gfg" here: 'g' comes: 2 times 's' comes: 2 times 'a' comes: 2 times 'h' comes: 1 time 'o' comes: 1 time 'k' comes: 1 time 'v' comes: 1 time 'e' comes: 1
2 min read
Check missing dates in Pandas
In this article, we will learn how to check missing dates in Pandas. A data frame is created from a dictionary of lists using pd.DataFrame() which accepts the data as its parameter. Note that here, the dictionary consists of two lists named Date and Name. Both of them are of the same length and some dates are missing from the given sequence of date
4 min read