Editor

Python Program to Find the Missing Number in a List

Intermediate · Lists

This program takes a list that should hold every number from 1 to n, in any order, but has one number missing, and finds the missing one. It uses the formula for the sum of 1 to n: whatever the list falls short of that sum is the missing number.

Program

missing_number.py
numbers = [1, 2, 4, 6, 3, 7, 8] # the numbers 1 to 8, with one missing
n = len(numbers) + 1 # the full list would have one more number
expected_sum = n * (n + 1) // 2 # 1 + 2 + ... + n
actual_sum = sum(numbers)
missing = expected_sum - actual_sum
print("List:", numbers)
print(f"Sum of 1 to {n} should be {expected_sum}")
print(f"Sum of the list is {actual_sum}")
print("Missing number:", missing)
Output
List: [1, 2, 4, 6, 3, 7, 8]
Sum of 1 to 8 should be 36
Sum of the list is 31
Missing number: 5

How it works

  1. With one number missing, the full list would have len(numbers) + 1 numbers, so n is 8.
  2. The sum 1 + 2 + ... + n always equals n * (n + 1) // 2, which is 36 for n = 8.
  3. The numbers in the list add up to 31, so the missing number is 36 - 31 = 5.
  4. This needs only one pass over the list, and the order of the numbers does not matter.

Other ways to write it

Finding several missing numbers with sets

Finding several missing numbers with sets
numbers = [3, 7, 1, 2, 8, 4, 10]
full = set(range(1, max(numbers) + 1)) # every number from 1 to the largest
missing = sorted(full - set(numbers))
print("Missing numbers:", missing)
Output
Missing numbers: [5, 6, 9]

The set difference gives every number that should be there but is not, so it also works when more than one number is missing.

Checking each number in turn

Checking each number in turn
numbers = [1, 2, 4, 6, 3, 7, 8]
for i in range(1, len(numbers) + 2):
if i not in numbers:
print("Missing number:", i)
Output
Missing number: 5

The simplest idea: try every number from 1 to n and report the one that is not in the list. It is slower, because in searches the list each time.

Try it yourself

Take out a different number, for example 1 or 8, and check that the program still finds it.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises