57

If I have a string list ,

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

how can I remove the duplicates from the list?

1

4 Answers 4

107

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

Sign up to request clarification or add additional context in comments.

Comments

17

Use the set type to remove duplicates

a = list(set(a))

Comments

6

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

a = [ ... ]
s = set(a)
a2 = list(s)

Comments

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 !

2 Comments

does this code snippet preserve the order?
It does preserve order, but has quadratic complexity, and that is bad for any list remotely big.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.