-1

I am trying to remove the duplicates from a list. First tried to do so by comparing the elements of 2 lists but i am no satisfied with this method. Is there an easier way?

list1 = [a, b, b, c, c, d,]
list2 = [b, c]
for list1 in list2:
   list.append(list.remove())
return list

But this way i remove all of the members that are in list1 and list2 and i want to remove only the duplicates.

4 Answers4

0

You can try this

readmelist.sort()
readmelist = list(dict.fromkeys(readmelist))
char
  • 2,063
  • 3
  • 15
  • 26
codingdiet
  • 43
  • 2
0

This will generate a new list called 'list' that contains no duplicat items. Also note that you have an extra , at the end of list1 which will cause errors and that a is read as a variable, to read it as a string use 'a'.

list1 = ['a', 'b', 'b', 'c', 'c', 'd']
list2 = ['b', 'c']
list = []
for i in list1:
    if i not in list2:
        list.append(i)
print(list)
BillyN
  • 185
  • 2
  • 10
0

to the issue removing duplicates:

list1=list(set(list1))

But I honestly don't know what you want with your second list. If you want to remove all items which are in the second list from list one use a for loop. If you want to remove all items which are in the second list and several times in the first one, you should use a for loop with a counter and only remove the entry if counter >=1. For the last case even better would be using a mask and then remove the values (you do not have to loop over your list over and over this way).

Maybe you want something like

list_out= list( set(list1) - set(list2))

EDIT: just saw this is a duplicate question from here and therefore should be closed.

Arbor Chaos
  • 149
  • 6
0

Easiest way that I have found so far is using dictionary.

list1 = [a, b, b, c, c, d,] list1 = list(dict.fromkeys(list1))

dict.fromkeys(object) creates a dictionary with keys but no values.

Since a dictionary can only have unique keys, duplicates are automatically removed.

We then cast the dictionary into a list using list('Dictionary_Here')

Hope this helps.

Harshit
  • 1
  • 1