-2

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

I have list of integers in Python. Some of the values are present several times in the list. What is an elegant way to get list out of first list, where each element is presented once?

Community
  • 1
  • 1
ashim
  • 24,380
  • 29
  • 72
  • 96

4 Answers4

3

One nice way that isn't guaranteed to maintain the ordering:

l = list(set(l))
Rik Poggi
  • 28,332
  • 6
  • 65
  • 82
Guy Adini
  • 5,188
  • 5
  • 32
  • 34
1

list(set(your_list))

But if you don't want duplicates, maybe you should be using a set instead of a list in the first place?

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
0

Using set:

dup_list = (1,2,2,3,3,3)
cleaned_list = list(set(dup_list))
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
istruble
  • 13,363
  • 2
  • 47
  • 52
0

Use itertools.groupby ( http://docs.python.org/library/itertools.html#itertools.groupby ).

From the docs: [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B

You will likely wish to use sorted also.

Marcin
  • 48,559
  • 18
  • 128
  • 201