Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Append Missing Elements from Other List
Next article icon

Python | Find missing elements in List

Last Updated : 06 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, we can get elements in range as input but some values are missing in otherwise consecutive range. We might have a use case in which we need to get all the missing elements. Let's discuss certain ways in which this can be done. 

Method #1 : Using list comprehension We can perform the task of finding missing elements using the range function to get the maximum element fill and then insert the elements if there is a miss. 

Python3
# Python3 code to demonstrate # Finding missing elements in List # using list comprehension  # initializing list test_list = [3, 5, 6, 8, 10]  # printing original list print('The original list : ' + str(test_list))  # using list comprehension # Finding missing elements in List res = [ele for ele in range(max(test_list)+1) if ele not in test_list]  # print result print('The list of missing elements : ' + str(res)) 

Output
The original list : [3, 5, 6, 8, 10] The list of missing elements : [0, 1, 2, 4, 7, 9]

Time Complexity: O(n) where m and n is the number of elements in the list. list comprehension performs n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list

  Method #2 : Using set() This problem can also be performed using the properties of difference of set and then getting the elements that are missing in a range. 

Python3
# Python3 code to demonstrate # Finding missing elements in List # Using set()  # initializing list test_list = [3, 5, 6, 8, 10]  # printing original list print('The original list :' + str(test_list))  # Using set() # Finding missing elements in List res = list(set(range(max(test_list) + 1)) - set(test_list))  # print result print('The list of missing elements :' + str(res)) 

Output
The original list :[3, 5, 6, 8, 10] The list of missing elements :[0, 1, 2, 4, 7, 9]

Time Complexity: O(n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

Method #3 : Using difference() method of the set data type

Here is another alternative approach using the difference() method of the set data type to find missing elements in a list in Python:

Python3
test_list = [3, 5, 6, 8, 10]  # Find maximum element in test_list max_ele = max(test_list)  # Convert test_list to set and find difference with set of elements in range from 0 to max_ele res = set(range(max_ele+1)).difference(set(test_list))  print("The original list:", test_list) print("The list of missing elements:", list(res)) #This code is contributed by Edula Vinay Kumar Reddy 

Output
The original list: [3, 5, 6, 8, 10] The list of missing elements: [0, 1, 2, 4, 7, 9]

This approach has a time complexity of O(n), as it requires a single call to the difference() method on sets of size n. The auxiliary space is O(n), as a new set is created to store the missing elements.

Note: Like the previous approach, this approach will only find missing elements within the range from 0 to max_ele. If the list test_list contains elements outside of this range, they will not be included in the resulting list of missing elements. To find missing elements within a different range, you can adjust the arguments of the range() function accordingly.

Method#4: Using Recursive method.

Python3
def find_missing_numbers(test_list, max_ele, result=None):     if result is None:         result = set(range(max_ele + 1))      if not test_list:         return list(result)      current_element = test_list.pop()     result.discard(current_element)      return find_missing_numbers(test_list, max_ele, result)  test_list = [3, 5, 6, 8, 10] max_ele = max(test_list) print("The original list:", test_list) missing_numbers = find_missing_numbers(test_list, max_ele) print("The list of missing elements:", missing_numbers) #this code contributed by tvsk 

Output
The original list: [3, 5, 6, 8, 10] The list of missing elements: [0, 1, 2, 4, 7, 9]

Time Complexity: O(n)

Auxiliary Space: O(n)

Method#5: Using NumPy module

step-by-step algorithm for implementing the approach:

  1. Import the NumPy module.
  2. Initialize the test_list with a list of integers.
  3. Convert the test_list to a NumPy array using the np.array() function.
  4. Find the maximum element in the test_array using the max() method.
  5. Use NumPy's arange() function to generate an array of numbers from 0 to max_element + 1.
  6. Use NumPy's setdiff1d() function to find the set difference between the generated array and the test_array.
  7. Store the result in res.
  8. Print the original list and the missing elements.
Python3
# import NumPy module import numpy as np  # initialize the test_list test_list = [3, 5, 6, 8, 10]  # convert the test_list to a NumPy array test_array = np.array(test_list)  # use NumPy's setdiff1d() function to find the missing elements res = np.setdiff1d(np.arange(test_array.max() + 1), test_array)  # print the original list and the missing elements print("The original list : " + str(test_list)) print("The list of missing elements : " + str(res)) 

Output

The original list : [3, 5, 6, 8, 10] The list of missing elements : [0 1 2 4 7 9]


Time Complexity:

  • Finding the maximum element in the test_array takes O(n) time where n is the length of the test_array.
  • Generating an array of numbers using arange() takes O(max_element) time.
  • Computing the set difference using setdiff1d() takes O(max_element) time.
  • Overall, the time complexity of the algorithm is O(max_element + n).


Auxiliary Space Complexity:

  • Creating the NumPy array using np.array() takes O(n) space.
  • Generating the array of numbers using arange() takes O(max_element) space.
  • Computing the set difference using setdiff1d() takes O(max_element) space.
  • Overall, the auxiliary space complexity of the algorithm is O(max_element + n).
  • Note that this algorithm assumes that the list test_list contains non-negative integers. If the list contains negative integers or floats, the approach needs to be modified accordingly.

Method 6: Using the filter() function and the lambda function 

step-by-step algorithm for implementing the approach:

  1. Define the function using a lambda function that takes an element x and checks if it is not in the my_list using the not in operator. This function will be used by the filter() function to filter out the elements that are not missing.
  2. Use the filter() function and range(start_range, end_range+1) as arguments to filter out the missing elements from the range.
  3. Convert the filtered result to a list using the list() function.
  4. Return the list of missing elements.
Python
# Define the list and the range of elements to check for my_list = [3, 5, 6, 8, 10] start_range = 0 end_range = 10  # Use the filter() function and a lambda function to find the missing elements missing_elements = list(filter(lambda x: x not in my_list, range(start_range, end_range+1)))  # Print the missing elements print(missing_elements) 

Output
[0, 1, 2, 4, 7, 9]

Time Complexity:

  • The range of elements to be checked for is produced in O(1) time by the range() function.
  • The lambda function in use by filter() checks whether such a missing element exists in O(1) time.
  • The length of the range, n, specifies how long it's going to take the filter() function to remove the missing elements.
  • The filtered result is formed into a list in O(n) time by the list() function.
  • As a result, this method has an overall time complexity of O(n), where n is just the length of the range.

Space Complexity:

Both the range() and the lambda functions used by filter() occupy O(1) space, therefore they do not add to the complexity of the entire space.

Method 7: Using the pandas Package-

Note: first install pandas by using - pip install pandas

  • Creating a Dataframe from the test_list.
  • Creating a range of numbers in the DataFrame.
  • Performing merge on the dataframe and the range dataframe, filling the missing values.
  • Filtering the DataFrame to show only the rows where the column value is missing.
  • Finding the values from the DataFrame and converting them to a list.
Python3
import pandas as pd  # original list test_list = [3, 5, 6, 8, 10]  # create a series with all values from 0 to the max value in the list s = pd.Series(range(max(test_list)+1))  # use set difference to find the missing values result = list(set(s) - set(test_list))  print("The original list:", test_list) print("The list of missing elements:", result) 

Output

The original list : [3, 5, 6, 8, 10] The list of missing elements : [0 1 2 4 7 9]

Time Complexity: O(N) where n is the length of the list, as it we have to traverse the whole list.

Space Complexity: O(N)  as we are creating a new pandas series of max length N.


Next Article
Python - Append Missing Elements from Other List
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - List Elements Grouping in Matrix
    Given a Matrix, for groups according to list elements, i.e each group should contain all elements from List. Input : test_list = [[2, 6], [7, 8], [1, 4]], check_list = [1, 2, 4, 6] Output : [[7, 8], [[1, 2], [4, 6]]] Explanation : 1, 2, 4, 6 elements rows are grouped. Input : test_list = [[2, 7], [7
    8 min read
  • Python - Elements Lengths in List
    Sometimes, while working with Python lists, can have problem in which we need to count the sizes of elements that are part of lists. This is because list can allow different element types to be its members. This kind of problem can have application in many domains such has day-day programming and we
    6 min read
  • Python - Append Missing Elements from Other List
    We are given two lists, and our task is to append elements from the second list to the first list, but only if they are not already present. This ensures that the first list contains all unique elements from both lists without duplicates. For example, if a = [1, 2, 3] and b = [2, 3, 4, 5], the resul
    3 min read
  • Python - Minimum element indices
    Sometimes, while working with Python lists, we can have a problem in which we intend to find the position of minimum element of list. This task is easy and discussed many times. But sometimes, we can have multiple minimum elements and hence multiple minimum positions. Let’s discuss a shorthand to ac
    3 min read
  • Find index of element in array in python
    We often need to find the position or index of an element in an array (or list). We can use an index() method or a simple for loop to accomplish this task. index() method is the simplest way to find the index of an element in an array. It returns the index of the first occurrence of the element we a
    2 min read
  • Python | Check if element exists in list of lists
    Given a list of lists, the task is to determine whether the given element exists in any sublist or not. Given below are a few methods to solve the given task. Method #1: Using any() any() method return true whenever a particular element is present in a given iterator. C/C++ Code # Python code to dem
    5 min read
  • Remove Multiple Elements from List in Python
    In this article, we will explore various methods to remove multiple elements from a list in Python. The simplest way to do this is by using a loop. A simple for loop can also be used to remove multiple elements from a list. [GFGTABS] Python a = [10, 20, 30, 40, 50, 60, 70] # Elements to remove remov
    3 min read
  • Python - Odd elements indices
    Sometimes, while working with Python lists, we can have a problem in which we wish to find Odd elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Let’s discuss certain way to find indic
    7 min read
  • Uncommon Elements in Lists of List - Python
    We are given two lists of lists and our task is to find the sublists that are uncommon between them. (a sublist is considered uncommon if it appears in only one of the lists and not in both.) For example: a = [[1, 2], [3, 4], [5, 6]] and b = [[3, 4], [5, 7], [1, 2]] then the output will be [[5, 6],
    4 min read
  • Find element in Array - Python
    Finding an item in an array in Python can be done using several different methods depending on the situation. Here are a few of the most common ways to find an item in a Python array. Using the in Operatorin operator is one of the most straightforward ways to check if an item exists in an array. It
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences