'How do I compare two lists in python

I have two lists. The first list contains only strings (basically, it contains foreign words) and the second list contains only strings (it's composed of the words the user already knows). I want to compare the two lists and remove from list 1 the words of list 2. How can I do that?

My attempt:

   all_words = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
        
   def compare_lists (all_words):
       known_words = ['A', 'B', 'C', 'D', 'E',]
       for i in all_words:
           if i in known_words:
               all_words.remove(i)
       return all_words
   
   unknown_words = compare_lists(all_words)
   
   print(unknown_words)

Expected output: F, G, H, I.

A long story short, the code doesn't work. I can't quite pinpoint what it does but it seems to remove only one word from the "all_words" list (probably, the code doesn't even work at all but that's just my impression).

Thank you in advance.



Solution 1:[1]

You could use set() https://docs.python.org/3/library/functions.html#func-set:

for example :

s1 = set(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'])
s2 = set(['A', 'B', 'C', 'D', 'E', 'F'])

final_words = s1 - s2

print(final_words)
# {'H', 'I', 'G'}

Solution 2:[2]

The problem with your code is that you're deleting the elements in the same array on which you're iterating. You can try this:

all_words = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
def compare_lists (all_words):
    known_words = ['A', 'B', 'C', 'D', 'E']
    temp = all_words[:]

    for i in temp:
        if i in known_words:
            all_words.remove(i)
    return all_words
   
unknown_words = compare_lists(all_words)

Output:

['F', 'G', 'H', 'I']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Enzo Ramirez C.
Solution 2