-3

I tried the following code but it doesn't seem to remove any duplicates

list2 = [element for element in list1 if element not in list2]

however,

    for i in list1:
        if i not in list2:
            list2.append(i)


   

this code works perfectly fine, can anyone please let me know why is this the case?

ariescode
  • 1
  • 1
  • ```list2 = [element for element in list1 if element not in list2]``` because ```list2``` is not properly defined. You are creating a list named ```list2``` and in the list comprehension, checking if the elements are there in ```list2``` –  Aug 06 '21 at 06:40
  • @Xitiz Telling why it doesn't work –  Aug 06 '21 at 06:42
  • @Sujay probably not refreshed in mine :) – imxitiz Aug 06 '21 at 06:43
  • I use `newlist = list(set(list1))` where `list1` has duplicates and `newlist` is a list which does not have duplicates. – Keshav Bajaj Aug 06 '21 at 06:44

1 Answers1

0

It's producing an identical list as list2 contains no elements at run-time. What you'd want is this:

list1 = [1, 2, 3, 3, 5, 9, 6, 2, 8, 5, 2, 3, 5, 7, 3, 5, 8]
list2 = []
[list2.append(item) for item in list1 if item not in list2]
print(list2)
HiEd
  • 160
  • 3