Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find missing elements between two elements in a list in Python?

I have a list as follows:

['1', '5', '6', '7', '10']

I want to find the missing element between two elements in the above list. For example, I want to get the missing elements between '1' and '5', i.e. '2', '3' and '4'. Another example, there are no elements between '5' and '6', so it doesn’t need to return anything.

Following the list above, I expect it to return a list like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['2', '3', '4', '8', '9']

How to return the above list? I would appreciate any help. Thank you in advance!

>Solution :

Using a classic for loop and range() method and also for one-liner fans:

arr = ['1', '5', '6', '7', '10']
ans = []

for i in range(len(arr) - 1): ans += map(str, list(range(int(arr[i]) + 1, int(arr[i + 1]))))
    
print(ans)

outputs: ['2', '3', '4', '8', '9']

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading