Abdullah Bilal Abdullah Bilal - 1 year ago 116
Python Question

How to check if a list already contains an element in Python?

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.

fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
words = line.split()
if lst.count(words) == 0:
lst = lst + words
print lst

Answer Source

Use a set(), it ensures unique elements. Alternatively, you can use the in operator to check for membership in a list (albeit an order of magnitude less efficient).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download