Find missing numbers in a sorted list range in Python


Given a list with sorted numbers, we want to find out which numbers are missing from the given range of numbers.

With range

we can design a for loop to check for the range of numbers and use an if condition with the not in operator to check for the missing elements.

Example

 Live Demo

listA = [1,5,6, 7,11,14]

# Original list
print("Given list : ",listA)

# using range
res = [x for x in range(listA[0], listA[-1]+1)
                              if x 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 :
[2, 3, 4, 8, 9, 10, 12, 13]

with ZIP

The ZIP function

Example

 Live Demo

listA = [1,5,6, 7,11,14]

# printing original list
print("Given list : ",listA)

# using zip
res = []
for m,n in zip(listA,listA[1:]):
   if n - m > 1:
      for i in range(m+1,n):
         res.append(i)

# 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 :
[2, 3, 4, 8, 9, 10, 12, 13]

Updated on: 26-Aug-2020

749 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements