I'm trying to remove words from one list that appear in another. Then I have to copy the ones that are not repeated in a third list. When I make a comparison I have a problem with the list index

The language is python, last version.

listOne = ['Hello','Every','One','Here']                       
listTwo = ['Every','Here','Hi','Nice']
listThree = []

for i in range(len(listOne)):
    for j in range(len(listTwo)):
       if listOne[i] == listTwo[j]: # <-- error here
            listOne.remove(listOne[i])

 #Here is the problem
 if listOne[i] == listTwo[j]]: 
 IndexError: list index out of range

I want to know why this happens.

3 Answers

0
kogito On Best Solutions

You can use list expressions to fill in list3, and a for loop and the in statement for the first requirement:

listOne = ['Hello','Every','One','Here']                       
listTwo = ['Every','Here','Hi','Nice']
listThree = [word for word in listOne if not(word in listTwo)]

for word in [word for word in listOne if word in listTwo]:
    listOne.remove(word)
2
Gustav Rasmussen On

Use a list comprehension:

listThree = [i for i in listOne if i not in listTwo]
0
J. Antunes On

You can use sets to compare lists and remove duplicates

>>> listOne = ['Hello','Hello','Every','One','Here']
>>> listTwo = ['Every','Here','Hi','Nice']
>>> listThree = list( set(listOne) - set(listTwo) )
>>> listThree
['Hello', 'One']