How can I find the duplicates in a Python list and create another list of the duplicates? The list only contains integers.
I am entering much much late in to this discussion. Even though, I would like to deal with this problem with one liners . Because that's the charm of Python. if we just want to get the duplicates in to a separate list (or any collection),I would suggest to do as below.Say we have a duplicated list which we can call as 'target'
target=[1,2,3,4,4,4,3,5,6,8,4,3]
Now if we want to get the duplicates,we can use the one liner as below:
duplicates=dict(set((x,target.count(x)) for x in filter(lambda rec : target.count(rec)>1,target)))
This code will put the duplicated records as key and count as value in to the dictionary 'duplicates'.'duplicate' dictionary will look like as below:
{3: 3, 4: 4} #it saying 3 is repeated 3 times and 4 is 4 times
If you just want all the records with duplicates alone in a list, its again much shorter code:
duplicates=filter(lambda rec : target.count(rec)>1,target)
Output will be:
[3, 4, 4, 4, 3, 4, 3]
This works perfectly in python 2.7.x + versions