How to find a missing number from a list?

Viewed 39338

How do I find the missing number from a sorted list the pythonic way?

a=[1,2,3,4,5,7,8,9,10]

I have come across this post but is there a more and efficient way to do this?

18 Answers

This will handle the cases when the first or last number is missing.

>>> a=[1,2,3,4,5,7,8,9,10]
>>> n = len(a) + 1
>>> (n*(n+1)/2) - sum(a)
6

Simple solution for the above problem, it also finds multiple missing elements.

a = [1,2,3,4,5,8,9,10]
missing_element = []
for i in range(a[0], a[-1]+1):
    if i not in a:
        missing_element.append(i)

print missing_element

o/p: [6,7]

Here is the simple logic for finding mising numbers in list.

l=[-10,-5,2,4,5,9,20]
s=l[0]
e=l[-1]
x=sorted(range(s,e+1))
l_1=[]
for i in x:
    if i not in l:
        l_1.append(i)
print(l_1)
def findAllMissingNumbers(a):
   b = sorted(a)
   return list(set(range(b[0], b[-1])) - set(b))
L=[-5,1,2,3,4,5,7,8,9,10,13,55]

missing=[]

for i in range(L[0],L[-1]):
    if i not in L:
        missing.append(i)
print(missing)

There is a perfectly working solution by @Abhiji. I would like to extent his answer by the option to define a granularity value. This might be necessary if the list should be checked for a missing value > 1:

from itertools import imap, chain
from operator import sub

granularity = 3600
data = [3600, 10800, 14400]

print list(
  chain.from_iterable(
    (data[i] + d for d in xrange(1, diff) if d % granularity == 0) 
      for i, diff in enumerate(imap(sub, data[1:], data)) 
        if diff > granularity
  )
)

The code above would produce the following output: [7200].

As this code snipped uses a lot of nested functions, I'd further like to provide a quick back reference, that helped me to understand the code:

Less efficient for very large lists, but here's my version for the Sum formula:

def missing_number_sum(arr):
    return int((arr[-1]+1) * arr[-1]/2) - sum(arr)

If the range is known and the list is given, the below approach will work.

a=[1,2,3,4,5,7,8,9,10]
missingValues = [i for i in range(1, 10+1) if i not in a]
print(missingValues)

# o/p: [6] 
Related