2

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]

Vinay
  • 21
  • 3
  • Does this answer your question? [Removing duplicates in the lists](https://stackoverflow.com/questions/7961363/removing-duplicates-in-the-lists) – gen_Eric Feb 08 '21 at 18:16
  • Please provide the code and the correct output. Using set() should be the correct way to approach this. – JarroVGIT Feb 08 '21 at 18:16

1 Answers1

3

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]
user2390182
  • 72,016
  • 6
  • 67
  • 89