Lucas Mähn Lucas Mähn - 1 month ago 6
Python Question

compare two lists (python)

I need to compare two lists in a program to see if there are matching strings. One of them is a txt document that I already imported. Thats what I did

def compareLists(self, listA, listB):
sameWords = list()

for a in xrange(0,len(listA)):
for b in xrange(0,len(listB)):
if listA[a] == listB[b]:
sameWords.append(listA[a])
pass
pass
pass
return sameWords


But if I run the program it doesnt show any matches although I know that there has to be one. I think its somewhere inside the if block.

Answer

I am assuming the indentation is correct in your code. Continuing with your strategy, this code should work.

def compareLists(self, listA, listB):
    sameWords = list()

    for a in xrange(0,len(listA)):
        for b in xrange(0,len(listB)):
            if listA[a] == listB[b]:
                sameWords.append(listA[a])
    return sameWords

Alternatively, as @Efferalgan suggested, simply do the set intersection.

def compareLists(self, listA, listB):
    return list(set(listA) & set(listB))

Note: The set intersection will remove duplicate matching words from your result.

As you said, you are reading in the lines from a text file, and it looks like the newlines are still in there.

my_text_list = [s for s in open("my_text.txt").read().rsplit()]