Total Pageviews

Donate

Dec 14, 2010

Removing duplicate Items from a python List with a single line of code !!

It is very common that you have generated a list and it has duplicates. And for a reason or another you wanna remove these duplicate.

For sure you may construct an empty list and go for each element in the original one and if it is not in this unique list you append the element to the unique list.
The following lined of code illustrate that idea
>>>myList=[1,1,2,2,'a','a','b','b']
>>>uniqueList=[]
>>>for ele in myList:
>>>... if ele not in uniquList:
>>>... uniquList.append(ele)

>>>uniqueList
[1,2,'a','b']
>>>

you know, it works ... but many lines of code to do such a simple thing ... REMOVE the DUPLICATES !!!

Here is the optimum way ... using Sets
simply convert the list to a set and then convert to list again ... lets see how
>>>myList=[1,1,2,2,'a','a','b','b']
>>>uniquList = list( set(myList) )
>>>uniqueList
[1,2,'a','b']

yah ... that's true ... very simple and straightforward :)

2 comments:

Donate