How to check if a list already contains an element in Python?
<p>i have been working on this for quite a time and my if statement does not seem to have any effect on the code. what I am trying to do is that I want to enter words in a list without repetition.</p>

<pre><code>fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    line.rstrip()
    words = line.split()
    if lst.count(words) == 0:
        lst = lst + words
    lst.sort()
print lst
</code></pre>

<p>Use a <a href="https://docs.python.org/2/library/sets.html" rel="nofollow"><code>set()</code></a>, it ensures unique elements. Alternatively, you can use the <a href="https://docs.python.org/3/reference/expressions.html#membership-test-operations" rel="nofollow"><code>in</code></a> operator to check for membership in a list (<em>albeit an order of magnitude less efficient</em>).</p>

python python-2.7 python-3.x