Vinay
Vinay

Reputation: 31

How to remove duplicates elements in the list in Python

For example in the below list

l=[1, 2, 3, 'hello', "world", True, 10, 1, 2, 3, 'hello', True, 10, 1, 2, 3, 'hello', True] ,  

I'm not able to retain the occurrence of the keyword True. I have used different methods like for loop to iterate over each elements in the list and appending it to the new list if doesn't exists in the new list(naive method), list comprehension, built in function like set().

I'm getting the below output which is incorrect !!

[1, 2, 3, 'hello', 'world', 10]

please assist me to solve this issue

The code that I have written

ll=[]
for i in l :
    if i not in ll :
       ll.append(i)
        
print(ll)

output I'm getting = [1, 2, 3, 'hello', 'world', 10] expected output = [1, 2, 3, 'hello', 'world', True, 10]

Upvotes: 2

Views: 59

Answers (1)

user2390182
user2390182

Reputation: 73498

The issue is that 1 == True and object equality is what contains checks test. You would have to test for type equality, too:

l = [1, 2, 3, 'hello', "world", True, 10, 1, 2, 3, 'hello', True, 10, 1, 2, 3, 'hello', True]

no_dupes = [x for x, _ in {(x, type(x)) for x in l}]
# [2, 3, 10, True, 1, 'world', 'hello']

Or, adapting your loop approach (which preserves order of occurrence):

ll = []
s = set()
for i in l:
    if (i, type(i)) not in s:
        s.add((i, type(i)))
        ll.append(i)
        
print(ll)
# [1, 2, 3, 'hello', 'world', True, 10]

Upvotes: 3

Related Questions