3

Possible Duplicate:
How do you remove duplicates from a list in Python whilst preserving order?

Let us consider the list:

x = ['a', 'b', 'c', 'c', 'a', 'd', 'z', 'z']

I want to delete these duplicate values list-x and want the result as:

y = ['a', 'b', 'c', 'd', 'z']
Community
  • 1
  • 1
Siddhu
  • 327
  • 7
  • 16

3 Answers3

12

If ordering doesn't matter, use a set:

>>> list(set(['a', 'b', 'c', 'c', 'a', 'd', 'p', 'p']))
['a', 'p', 'c', 'b', 'd']

If ordering does matter, use an OrderedDict:

>>> from collections import OrderedDict 
>>> OrderedDict.fromkeys(['a', 'b', 'c', 'c', 'a', 'd', 'p', 'p']).keys()
['a', 'b', 'c', 'd', 'p']
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • +1, Just a remarque no need for passing 0 to ``OrderedDict.fromkeys`` just ``OrderedDict.fromkeys(['a', 'b', 'c', 'c', 'a', 'd', 'p', 'p']).keys()`` – mouad Jul 18 '12 at 12:43
  • +1 for a neat solution that preserves order easily – Levon Jul 18 '12 at 13:33
4

Since nothing was stated about preserving order, this approach will work:

x = ['a', 'b', 'c', 'c', 'a', 'd', 'z', 'z']

list(set(x))

will give you

['a', 'c', 'b', 'd', 'z']

By changing your list to a set you eliminate all duplicates. You apply list() to change your non-duplicate data back to a list.

Levon
  • 138,105
  • 33
  • 200
  • 191
2

You could also use

y=[ x[i] for i in range(len(x)) if not x[i] in x[:i]]

I think that this would be the simplest solution possible.

hfhc2
  • 4,182
  • 2
  • 27
  • 56