# How to Remove Undirected Edges that are the Same [duplicate]

Given:

theData = {1 <-> 2, 2 <-> 3, 2 <-> 1}


I would like to remove any duplicates where I define a duplicate to be:

x <-> y == y <-> x


Have tried:

theRule = UndirectedEdge[p1_, p2_] :> UndirectedEdge[p2, p1]
DeleteDuplicates[theData, # == (# /. theRule) &]

• Bah, DeleteDuplicates[theGraphData, #1 == (#2 /. theRule) &] works. Any other creative ways of doing this? Oct 17, 2014 at 15:59
• I think that would fail for a data set of: {1--2,3--1,2--1} Oct 17, 2014 at 16:07

1. Sort the elements of theData:

DeleteDuplicates[Sort /@ theData]

{1 <-> 2, 2 <-> 3}

2. Use a function ue with Attribute Orderless:

SetAttributes[ue, Orderless];
UndirectedEdge @@@ DeleteDuplicates[ue @@@ theData]

{1 <-> 2, 2 <-> 3}


or

DeleteDuplicates[ue @@@ theData] /. ue -> UndirectedEdge

{1 <-> 2, 2 <-> 3}

3. Temporarily make UndirectedEdge Orderless:

SetAttributes[UndirectedEdge, Orderless];
DeleteDuplicates[theData]

{1 <-> 2, 2 <-> 3}


Use ClearAttributes[UndirectedEdge, Orderless] to reset the Attributes of UndirectedEdge back to {Protected, ReadProtected}.

You can convert your data to a graph and use SimpleGraph to get rid of the duplicates.

EdgeList@SimpleGraph@Graph@theData

{1 <-> 2, 2 <-> 3}


If you want to delete both true duplicates (i.e. 1<->2 is equal to 1<->2) and those that fulfill your definition of a duplicate you may try

DeleteDuplicatesBy[theData, Sort]


Otherwise you may try

DeleteDuplicates[theData, # === Reverse@#2 &]

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