11

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.

5 Answers5

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

Keys@Select[Counts[list], # == 1 &]
(* {3, 4, 5} *)
Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
  • 1
    Or more functional perhaps: Keys@Select[Counts[list], EqualTo[1]] – SHuisman Mar 01 '20 at 10:20
  • 4
    @SHuisman If you want to go operator, go all the way :-) Keys@Select[EqualTo[1]]@Counts[list] – Szabolcs Mar 01 '20 at 10:52
  • 4
    Keys@*Select[EqualTo[1]]@*Counts is even more operator. – Roman Mar 01 '20 at 13:15
  • 1
    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. – Mark R Mar 01 '20 at 19:06
8
With[{t = Tally[#]}, Pick[t[[All, 1]], t[[All, 2]], 1]] &

Should outperform, hardly "ingenious "...

ciao
  • 25,774
  • 2
  • 58
  • 139
7

Without pattern matching:

Sort[{1, 2, 1, 2, 3, 4, 5, 1}] // 
  Split // 
  Select[Length[#] == 1 &] //
  Flatten[#, 1] &
sakra
  • 5,120
  • 21
  • 33
7

For variety:

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

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

{3, 4, 5}

kglr
  • 394,356
  • 18
  • 477
  • 896
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}

kglr
  • 394,356
  • 18
  • 477
  • 896