
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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]
Advertisements