Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

Pretty much I need to write a program to check if a list has any duplicates and if it does it removes them and returns a new list with the items that weren't duplicated/removed. This is what I have but to be honest I do not know what to do.

def remove_duplicates():

      t = ['a', 'b', 'c', 'd'] 

      t2 = ['a', 'c', 'd'] 

      for t in t2:


     return t

1 Answer

0 votes
by (106k points)
edited by

To remove duplicate we can use set and pass it to the list()function:-

Below is an example that solves your problem :

t = [1, 2, 3, 1, 2, 5, 6, 7, 8] 


s = [1, 2, 3]

list(set(t) - set(s))


As we know sets themselves are unordered collections, so the order is lost after conversion. So we need to set it back to a list, for getting an arbitrary order.

The following code maintains the order of the elements after conversion:-

from collections import OrderedDict


To know more about this you can have a look at the following video tutorial:-

Related questions

Browse Categories