How to find the duplicates in a list and create another list with them?

Posted by Editorial Staff | Updated on

If you want to find the duplicates in a list and create another list with python? To remove duplicates use set(a). To print duplicates, something like:

Note that Counter is not particularly efficient (timings) and probably overkill here. set will perform better. This code computes a list of unique elements in the source order:

If list elements are not hashable, you cannot use sets/dicts and have to resort to a quadratic time solution (compare each with each). For example:


If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.

Related Questions & Answers