Python | Find missing elements in List
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 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)) |
The original list : [3, 5, 6, 8, 10] The list of missing elements : [0, 1, 2, 4, 7, 9]
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 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)) |
The original list : [3, 5, 6, 8, 10] The list of missing elements : [0, 1, 2, 4, 7, 9]
Recommended Posts:
- Python | Find missing numbers in a sorted list range
- Python | Find all elements count in list
- Python | Find elements of a list by indices
- Python program to find sum of elements in list
- Python | Find sum of frequency of given elements in the list
- Python | Find top K frequent elements from a list of tuples
- Python | Find common elements in list of lists
- Python program to find N largest elements from a list
- Python | Find the list elements starting with specific letter
- Python | Find missing and additional values in two lists
- Python | Merge List with common elements in a List of Lists
- Python | Add list elements with a multi-list based on index
- Python | Sorting list of lists with similar list elements
- Python | Replace elements in second list with index of same element in first list
- Python | Maximum sum of elements of list in a list of lists
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Akanksha_Rai