Home > OS >  Delete element from a list if it occurs in another list
Delete element from a list if it occurs in another list

Time:12-24

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 :

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 !

CodePudding user response:

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)

CodePudding user response:

I found a way with indexes too :

lst=["A","B","C"]
ma_var_lst = ["123A","564Z","Beee","CD152"]
indexes=[]

for elem in ma_var_lst:
    for letter in lst:
        if letter in elem:
            # get the index of the element
            index = ma_var_lst.index(elem)
            indexes.append(index)
            print("element: " elem)
            #ma_var_lst.remove(elem)

for i in sorted(indexes, reverse=True):
    del ma_var_lst[i]
print(ma_var_lst)
  • Related