Removing duplicate strings from a list in python

Question:

If I have a string list ,

a = ["asd","def","ase","dfg","asd","def","dfg"]

how can I remove the duplicates from the list?

Asked By: Shamika

||

Answers:

Use the set type to remove duplicates

a = list(set(a))
Answered By: Krumelur

Convert to a set:

a = set(a)

Or optionally back to a list:

a = list(set(a))

Note that this doesn’t preserve order. If you want to preserve order:

seen = set()
result = []
for item in a:
    if item not in seen:
        seen.add(item)
        result.append(item)

See it working online: ideone

Answered By: Mark Byers

You could pop ’em into a set and then back into a list:

a = [ ... ]
s = set(a)
a2 = list(s)
Answered By: rossipedia
def getUniqueItems(iterable):
result = []
for item in iterable:
    if item not in result:
        result.append(item)
return result

print (''.join(getUniqueItems(list('apple'))))

P.S. Same thing like one of the answers here but a little change, set is not really required !

Answered By: murasing
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.