1

I want to remove the duplicate elements in a list only when one element is repeated many times, like this:

li = ['Human','Human','Human'] => li = ['Human']

but not when there are two or more different elements:

li = ['Human','Monkey','Human', 'Human']
user202729
  • 3,358
  • 3
  • 25
  • 36
DGT
  • 2,604
  • 13
  • 41
  • 60
  • Isn't that what a `set` is? Why aren't you using a set? – S.Lott Sep 29 '10 at 22:18
  • @S.Lott: I did that mistake too, but read the second line.. ^^ – poke Sep 29 '10 at 22:20
  • @S. Lott. because he only wants duplicates removed if there is only one distinct value in the list. ordering might also be a concern. – aaronasterling Sep 29 '10 at 22:20
  • This is homework. I saw it last semester. http://stackoverflow.com/questions/1549509/remove-duplicates-in-a-list-while-keeping-its-order-python, http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t, etc. – S.Lott Sep 29 '10 at 22:23
  • Where did that answer disappear to? I thought that was correct? o.O – poke Sep 29 '10 at 22:28
  • @poke I deleted it but I guess the damage was already done. I dropped out of high school so I guess I don't mind stealing OP's education if they're giving it away for free. It would be nice if that came with a piece of paper but oh well. – aaronasterling Sep 29 '10 at 22:35

3 Answers3

4

You can do it easily with sets as below:

li = list(set(li))
DarthJDG
  • 16,511
  • 11
  • 49
  • 56
3
def clean(lst):
    if lst.count(lst[0]) == len(lst):
        return [lst[0]]
    else:
        return lst

Does that do what you want?

if so, then you can do it in place as well

def clean_in_place(lst):
    if lst.count(lst[0]) == len(lst):
        lst[:] = [lst[0]]
aaronasterling
  • 68,820
  • 20
  • 127
  • 125
  • That works great! btw was how do you clean duplicates if the successive elements are same, like ['a','a','a','b','a','a'] to ['a','b','a'] – DGT Sep 29 '10 at 22:52
2
lst = ['Human','Human','Human'] => lst = ['Human']
lst = ['Human','Monkey','Human', 'Human'] => lst = ['Human','Monkey','Human', 'Human']

it was do what you want?

if lst.count(lst[0])==len(lst):
   lst=list(set(lst))
   print lst 
else:
   print lst 
user1335578
  • 2,587
  • 2
  • 18
  • 15