# How to remove duplicate elements [duplicate]

How to remove duplicate elements? I want to delete all the same elements in a list. For example, list {1,2,1,2,3,4,5,1}, I want to get {3,4,5}.

And using DeleteDuplicates function can not achieve the desired purpose: DeleteDuplicates[{1, 2, 1, 2, 3, 4, 5, 1}]

I know this method at present: {1, 2, 1, 2, 3, 4, 5, 1} // Tally // Cases [{x_, 1}:> x], but I also want to know more ingenious methods.

• I think your Tally/*Cases method is pretty cool! Mar 1, 2020 at 9:27
• Does the order matter? Mar 1, 2020 at 9:47
• related Mar 1, 2020 at 15:07
• for fun: {1, 2, 1, 2, 3, 4, 5, 1} //. {a___, b_, c___, b_, d___} :> DeleteCases[{a, c, d}, b]. Mar 1, 2020 at 21:05
• @user1066 Thanks for linking that. This appears to be a duplicate and I am marking it as such. If I have missed an important distinction please let me know and I shall reopen. Mar 2, 2020 at 9:19

list = {1, 2, 1, 2, 3, 4, 5, 1};

Keys@Select[Counts[list], # == 1 &]
(* {3, 4, 5} *)
• Or more functional perhaps: Keys@Select[Counts[list], EqualTo[1]] Mar 1, 2020 at 10:20
• @SHuisman If you want to go operator, go all the way :-) Keys@Select[EqualTo[1]]@Counts[list] Mar 1, 2020 at 10:52
• Keys@*Select[EqualTo[1]]@*Counts is even more operator. Mar 1, 2020 at 13:15
• I like that this will preserve order. Several of the methods shown below do not. For example, switch the position of 3 and 4 and re-run the methods below. Instead of {4,3,5}, they return {3,4,5}. The method from OP also preserves the order. Mar 1, 2020 at 19:06
With[{t = Tally[#]}, Pick[t[[All, 1]], t[[All, 2]], 1]] &

Should outperform, hardly "ingenious "...

Without pattern matching:

Sort[{1, 2, 1, 2, 3, 4, 5, 1}] //
Split //
Select[Length[#] == 1 &] //
Flatten[#, 1] &

For variety:

lst = {1, 2, 1, 2, 3, 4, 5, 1};

lst //. {OrderlessPatternSequence[Repeated[x_, {2, ∞}], a___]} :> {a}

{3, 4, 5}

A Rube Goldberg solution:

☺1 /: {♯♯___, ☺1 @ ♯_, ♯♯♯___} := {♯♯, ♯♯♯} /. ♯ | ☺1 @ ♯ -> (## &[])
☺2 = (☺3 @ ♯_ := (☺3 @ ♯ = ☺1 @ ♯; ♯); ☺3 /@ #) &;

☺2 @ {1, 2, 1, 2, 3, 4, 5, 1}

{3, 4, 5}

• I LOL'd. +1 internet cookie for you.
– ciao
Mar 2, 2020 at 7:56
• I LOL'd. +1 internet cookie for you. Feb 26, 2021 at 2:40