45

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
  • 50,756
  • 12
  • 89
  • 148
Shamika
  • 473
  • 1
  • 4
  • 6

4 Answers4

87

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
  • 767,688
  • 176
  • 1,542
  • 1,434
12

Use the set type to remove duplicates

a = list(set(a))
Krumelur
  • 29,183
  • 6
  • 73
  • 115
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
  • 52,494
  • 10
  • 88
  • 90