compare two lists (python)
<p>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</p>

<pre><code>    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
</code></pre>

<p>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.</p>

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

<pre><code>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
</code></pre>

<p>Alternatively, as @Efferalgan suggested, simply do the set intersection.</p>

<pre><code>def compareLists(self, listA, listB):
    return list(set(listA) &amp; set(listB))
</code></pre>

<p><strong>Note:</strong> The set intersection will remove duplicate matching words from your result.</p>

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

<pre><code>my_text_list = [s for s in open("my_text.txt").read().rsplit()]
</code></pre>

python list