# Delete duplicates in a list, depending on the sequence of numbers

Below, list is a representative sample of my list, which contains lists of integers. I would like to be able to input:

list = {{1, 2, 3}, {3, 2, 1}, {2, 1, 3}};
f[list]


and obtain the output:

{{1, 2, 3}, {2, 1, 3}}


In other words, {3, 2, 1} is considered to be the same as {1, 2, 3}, since in reverse it is exactly {1, 2, 3}. However, {2, 1, 3} is not considered to be the same as either {1, 2, 3} or {3, 2, 1}, because it does not match these lists in forward or in reverse.

What function f can I use to accomplish this?

I tried this:

DeleteDuplicates[list, MemberQ[list, #] || MemberQ[Reverse /@ list, #] &]


but it does not work, although I'm not sure why.

Now suppose I want to input:

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


and obtain:

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


where the "second" {1, 2, 3} is removed as a "normal" duplicate. How can I do this? I could do:

DeleteDuplicates[DeleteDuplicates[list, (#1 == Reverse[#2] &)]]


but is there an easier way?

-

This should do the job:

DeleteDuplicates[list, SameQ[#1, #2] || SameQ[#1, Reverse@#2] &]

-
This is what I want. For list = {{1, 2, 3}, {3, 2, 1}, {2, 1, 3}, {1, 2, 3}};, it gives {{1, 2, 3}, {2, 1, 3}}. Thanks. – Andrew May 19 '12 at 19:39

If your application allows for reversed elements to be interchangeable you can do this:

DeleteDuplicates[Sort[{#, Reverse@#}][[1]] & /@ list]


The advantage here is speed; this is perhaps two orders of magnitude faster on large sets than the methods already presented.

-
This code works like a charm!! So fast! Not two orders faster, my test shows that it is at least three orders faster! It is necessary for large list. Thank you for your answer, Mr. Wizard! It solves my problem. – matheorem Oct 7 '15 at 8:34
@matheorem As always I'm glad I could help, and thanks for letting me know you found this three-year-old post useful. – Mr.Wizard Oct 7 '15 at 16:50

You can use your condition directly

 DeleteDuplicates[list, (#1 == Reverse[#2] &)]


or use Union with SameTest

 Union[list, SameTest -> (#1 == Reverse[#2] &)]


Edit: For the new requirement, you need to Or the conditions for "sameness" (as in @acl's answer)

 DeleteDuplicates[list, (#1 == Reverse[#2] || #1 == #2 &)]
Union[list, SameTest -> (#1 == Reverse[#2] || #1 == #2&)]

-
Okay, I think they both work now. Thanks. – Andrew May 19 '12 at 19:30
But now if list = {{1, 2, 3}, {3, 2, 1}, {2, 1, 3}, {1, 2, 3}} we get the duplicate element twice! – acl May 19 '12 at 19:32
@acl: Right, this is not what I wanted to happen, but I failed to specify this requirement in my original post. Please see my edit above. – Andrew May 19 '12 at 19:37
@Andrew I think my answer does do this in a simple way – acl May 19 '12 at 19:38