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']
6
  • Isn't that what a set is? Why aren't you using a set? Commented Sep 29, 2010 at 22:18
  • @S.Lott: I did that mistake too, but read the second line.. ^^ Commented Sep 29, 2010 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. Commented Sep 29, 2010 at 22:20
  • This is homework. I saw it last semester. stackoverflow.com/questions/1549509/…, stackoverflow.com/questions/89178/…, etc. Commented Sep 29, 2010 at 22:23
  • Where did that answer disappear to? I thought that was correct? o.O Commented Sep 29, 2010 at 22:28

3 Answers 3

4

You can do it easily with sets as below:

li = list(set(li))
Sign up to request clarification or add additional context in comments.

Comments

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]]

1 Comment

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']
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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.