If we have a list containing numbers, we can check if the numbers are contiguous or not and also find which numbers are missing from a range of numbers considering the highest number as the final value.
With range and max
We can design a for loop to check for absence of values in a range using the not in operator. Then capture all these values by adding them to a new list which becomes the result set.
Example
listA = [1,5,6, 7,11,14] # Original list print("Given list : ",listA) # using range and max res = [ele for ele in range(max(listA) + 1) if ele not in listA] # Result print("Missing elements from the list : \n" ,res)
Output
Running the above code gives us the following result −
Given list : [1, 5, 6, 7, 11, 14] Missing elements from the list : [0, 2, 3, 4, 8, 9, 10, 12, 13]
with set
We apply the set function to hold all the unique values for a given range and then subtracting the given list from it. So this gives the result set containing the missing values from the contiguous numbers.
Example
listA = [1,5,6, 7,11,14] # printing original list print("Given list : ",listA) # using set res = list(set(range(max(listA) + 1)) - set(listA)) # Result print("Missing elements from the list : \n" ,res)
Output
Running the above code gives us the following result −
Given list : [1, 5, 6, 7, 11, 14] Missing elements from the list : [0, 2, 3, 4, 8, 9, 10, 12, 13]