Find missing numbers in a sorted list range in Python

Given a sorted list of numbers, we want to find out which numbers are missing from the continuous range. Python provides several approaches to identify these gaps in the sequence.

Using range() with List Comprehension

We can create a complete range from the first to last element and check which numbers are not in the original list ?

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

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

# Find missing numbers using range
missing = [x for x in range(numbers[0], numbers[-1] + 1) 
           if x not in numbers]

# Result
print("Missing elements from the list:")
print(missing)
Given list: [1, 5, 6, 7, 11, 14]
Missing elements from the list:
[2, 3, 4, 8, 9, 10, 12, 13]

Using zip() to Find Gaps

The zip() function pairs consecutive elements, allowing us to detect gaps larger than 1 between adjacent numbers ?

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

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

# Find missing numbers using zip
missing = []
for current, next_num in zip(numbers, numbers[1:]):
    if next_num - current > 1:
        for i in range(current + 1, next_num):
            missing.append(i)

# Result
print("Missing elements from the list:")
print(missing)
Given list: [1, 5, 6, 7, 11, 14]
Missing elements from the list:
[2, 3, 4, 8, 9, 10, 12, 13]

Using set() for Better Performance

Converting the list to a set makes membership testing faster for large datasets ?

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

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

# Convert to set for faster lookup
number_set = set(numbers)
missing = [x for x in range(numbers[0], numbers[-1] + 1) 
           if x not in number_set]

# Result
print("Missing elements from the list:")
print(missing)
Given list: [1, 5, 6, 7, 11, 14]
Missing elements from the list:
[2, 3, 4, 8, 9, 10, 12, 13]

Comparison

Method Time Complexity Best For
List Comprehension with in O(n²) Small lists
Using zip() O(n) Memory efficient
Set-based approach O(n) Large datasets

Conclusion

Use the zip() method for memory efficiency or the set-based approach for large datasets. The list comprehension method works well for smaller lists with simple syntax.

Updated on: 2026-03-15T18:28:47+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements