简体   繁体   中英

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]

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM