DGT
DGT

Reputation: 2654

remove duplicate list elements

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

Upvotes: 1

Views: 710

Answers (3)

user1335578
user1335578

Reputation: 2747

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 

Upvotes: 2

user777847
user777847

Reputation:

You can do it easily with sets as below:

li = list(set(li))

Upvotes: 4

aaronasterling
aaronasterling

Reputation: 71004

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

Upvotes: 3

Related Questions