Python - Using set to filter duplicates

Introduction

Sets can be used to filter duplicates out of other collections.

Simply convert the collection to a set, and then convert it back again:

Demo

L = [1, 2, 1, 3, 2, 4, 5] 
print( set(L) )# from   w  ww .j  a  va 2  s .c  om
L = list(set(L))                                   # Remove duplicates 
print( L )
print( list(set(['yy', 'cc', 'aa', 'xx', 'dd', 'aa'])) )   # But order may change

Result

Related Topic