2 min read
Find the missing numbers in a given list or array using Python.
For example in the
arr = [1,2,4,5] the integer '
3' is the missing number.
There are multiple ways to solve this problem using Python. In this article, we will cover the most straightforward ones.
Step 1: Create an empty array for missing items
Step 3: Compare the loop variable with the given array if the value is not present append it to the missing array
Note: The array must be sorted for this to work. Use
arr.sort() on an unsorted array before feeding it to the program.
arr = [1,2,3,4,5,6,7,9,10] missing_elements =  for ele in range(arr, arr[-1]+1): if ele not in arr: missing_elements.append(ele) print(missing_elements)
arr = [1,2,3,4,5,7,6,9,10] missing_elemnts = [item for item in range(arr, arr[-1]+1) if item not in arr] print(missing_elemnts)
Using list comprehension we encapsulated the above solution in a single line.
Set() is a Python unordered mutable datatype that holds only unique values.
arr = [1,2,3,4,5,7,6,9,10] missing_value = set(range(arr, arr[-1]+1)) - set(arr) print(missing_value)
Here we created a set object of having values within the range of initial and final values of the provided array then compared it with the provided array to retrieve the missing value.
Instead of subtraction, we can also use the
difference() method of the
Latest from djangocentral
3 min read
4 min read