How do I find the duplicates in a list of integers and create another list of the duplicates?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
To remove duplicates use
set(a). To print duplicates, something like:Note that
Counteris not particularly efficient (timings) and probably overkill here.setwill perform better. This code computes a list of unique elements in the source order:or, more concisely:
I don’t recommend the latter style, because it is not obvious what
not seen.add(x)is doing (the setadd()method always returnsNone, hence the need fornot).To compute the list of duplicated elements without libraries:
or, more concisely:
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: