Show duplicates in Mathematica

duplicates, list, wolfram-mathematica

Solution

Lots of ways to do list extraction like this; here's the first thing that came to my mind:

Part[Select[Tally@x, Part[#, 2] > 1 &], All, 1]

Or, more readably in pieces:

Tally@x
Select[%, Part[#, 2] > 1 &]
Part[%, All, 1]

which gives, respectively,

{{1, 1}, {2, 1}, {3, 2}, {4, 1}, {5, 2}, {6, 1}}
{{3, 2}, {5, 2}}
{3, 5}

Perhaps you can think of a more efficient (in time or code space) way `:)`

By the way, if the list is unsorted then you need run `Sort` on it first before this will work.

Problem

In Mathematica I have a list: ``` x = {1,2,3,3,4,5,5,6} ``` How will I make a list with the duplicates? Like: ``` {3,5} ``` I have been looking at Lists as Sets, if there is something like Except[] for lists, so I could do: ``` unique = Union[x] duplicates = MyExcept[x,unique] ``` (Of course, if the x would have more than two duplicates - say, {1,2,2,2,3,4,4}, there the output would be {2,2,4}, but additional Union[] would solve this.) But there wasn't anything like that (if I did understand all the functions there well). So, how to do that?

Original source