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
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
- With one number missing, the full list would have
len(numbers) + 1numbers, sonis 8. - The sum 1 + 2 + ... + n always equals
n * (n + 1) // 2, which is 36 for n = 8. - The numbers in the list add up to 31, so the missing number is 36 - 31 = 5.
- 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
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
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.
Related programs
- Find the Sum of Natural Numbers
- Find the Sum of Elements in a List
- Find Duplicates in a List
- Find Pairs with a Given Sum
- Find the Largest and Smallest Number in a List
- Swap Elements at Even and Odd Positions in a List
- Find the Second Largest Number in a List
- Remove Duplicates from a List
- a Menu-Driven List
- Reverse a List
All Python programs · CBSE class 12 practical file · Python exercises