Search code examples
pythonlist-comprehension

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

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']