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

Delete element from a list if it occurs in another list

I posted my problem a little ago and i though i got the answer but still everything i saw didn’t help…

So i have two lists and i want that if an element from list1 is present in element of list2 delete the element from list2 but till now i didn’t find how to achieve this.

So for example i have those two lists :

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

lst_1=["A","B","C"]
lst_2 = ["123A","564Z","Beee","CD152"]

So i want to check if list_2 elements contains list_1 elements if so delete it !

So here for example i would like this output for a result_lst :

["564Z"] 

I tried to do like this :

lst=["A","B","C"]

ma_var_lst = ["123A","564Z","Beee","CD152"]


for elem in ma_var_lst:
    for letter in lst:
        if letter in elem:
            print("element: "+elem)
            ma_var_lst.remove(elem)
print(ma_var_lst)

but it won’t work as the index will move after deleting element….

If someone could help ! 🙂 Thanks !

>Solution :

I tried and this works for me.

lst = ["A", "B", "C"]
    
    ma_var_lst = ["123A", "564Z", "Beee", "CD152"]
    
    for letter in lst:
        for elem in ma_var_lst:
            for x in elem:
                if letter == x:
                    print(elem)
                    ma_var_lst.remove(elem)
                    break
    
    
    print(ma_var_lst)
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