53

If I have a string list ,

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

how can I remove the duplicates from the list?

Conrad Frix
  • 51,984
  • 12
  • 96
  • 155
Shamika
  • 553
  • 1
  • 4
  • 6

4 Answers4

101

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

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
15

Use the set type to remove duplicates

a = list(set(a))
Krumelur
  • 31,081
  • 7
  • 77
  • 119
6
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 !

murasing
  • 412
  • 6
  • 15
5

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

a = [ ... ]
s = set(a)
a2 = list(s)
rossipedia
  • 56,800
  • 10
  • 90
  • 93