2
$\begingroup$

Suppose I have a list of edges,

 {1 \[UndirectedEdge] 2, 1 \[UndirectedEdge] 3}

How do I get the 'invert' of the list,

 {2 \[UndirectedEdge] 1, 3 \[UndirectedEdge] 1}

I'm aware that both these lists will yield the same graph.

$\endgroup$
4
  • 2
    $\begingroup$ Map Reverse like Reverse /@ list $\endgroup$
    – Ben Izd
    Jul 30, 2022 at 7:16
  • 2
    $\begingroup$ @BenIzd This is not safe when dealing with edge tagged graphs. $\endgroup$
    – Szabolcs
    Jul 30, 2022 at 8:57
  • 2
    $\begingroup$ @Szabolcs Thanks for pointing that out. For that case, we could map SubsetMap[Reverse, ;; 2] $\endgroup$
    – Ben Izd
    Jul 30, 2022 at 9:04
  • $\begingroup$ @BenIzd Why don't you post an answer? $\endgroup$
    – Szabolcs
    Jul 30, 2022 at 9:16

2 Answers 2

6
$\begingroup$

You can use

UndirectedEdge[#2, #1, ##3] & @@@ edgelist

Reverse should not be applied to an UndirectedEdge as it may have more than two arguments in EdgeTaggedGraph.

$\endgroup$
3
$\begingroup$

If you're not working on EdgeTaggedGraph, then you can directly map Reverse like below:

Reverse /@ edgelist

Or with the second argument of Reverse (which is faster than mapping and uses less memory):

Reverse[edgelist, 2]

Or re-order the columns manually:

edgelist[[All, {2, 1}]]

In the case of EdgeTaggedGraph where all the edges are tagged, you can use:

edgelist[[All, {2, 1, 3}]]

Or generally:

SubsetMap[Reverse, ;; 2] /@ edgelist

But it's slower (~45 times) and uses more memory in comparison with Szabolcs's answer.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.