Home > Software design >  How do I compare two lists in python
How do I compare two lists in python

Time:05-04

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

Your code is good, but u made a mistake in the for loop.

Your code:

   for i in all_words:
       if i in known_words:
           all_words.remove(i)
   return all_words

Fixed:

for i in known_words:
    if i in all_words:
        all_words.remove(i)
return all_words
  • Related