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 can I remove part of an element in a list using the element of another list

So I have list_A and list_B and I need to remove whats in list_B from list_A Example:

list_A = ['I hate the world', 'I love my mother']
list_B = ['I hate', 'love my']

output: list_output = ['the world', 'I mother']

I tried to do

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

list_A = ['I hate the world', 'I love my mother']

list_B = ['I hate', 'love my']

list_output = [x for x in list_A if x not in list_B] 


print(list_output)

I have also tried a few other things I found on the internet, but they all threw errors or just didn’t do anything, and list comprehensions just seemed the most like what I was trying to achieve.

>Solution :

Here is one way to do it. You have to use nested loops so you can check all combinations until you find a match. Note that what I’m doing leaves the extra spaces in. You can add code to remove those from both halves.

list_A = ['I hate the world', 'I love my mother']
list_B = ['I hate', 'love my']

list_output = []
for phrase in list_A:
    for clause in list_B:
        if clause in phrase:
            i = phrase.find(clause)
            j = phrase[:i] + phrase[i+len(clause):]
            list_output.append(j)
            break
    else: # in case nothing was found
        list_output.append(phrase)

print(list_output)

Output:

[' the world', 'I  mother']
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