I want to know whether an edge exist between two specific vertex? Is there any function like EdgeExist[g,{v1,v2}]?


1 Answer 1


Yes, there is EdgeQ:

g = Graph[{1 -> 2, 2 -> 3, 3 -> 1}, VertexShapeFunction -> "Name"]

Mathematica graphics

{EdgeQ[g, 1 -> 2], EdgeQ[g, DirectedEdge[1, 2]], 
 EdgeQ[g, 1 <-> 2], EdgeQ[g, UndirectedEdge[1, 2]],
 EdgeQ[g, 2 -> 1], EdgeQ[g, DirectedEdge[2, 1]]}

{True, True, False, False, False, False}

If you need a function that takes a list of (unordered) vertices as the second arguments, you can use

edgeQ[g_, e : {_, _}] := Or @@ (EdgeQ[g, #] & /@ {DirectedEdge @@ e, 
     DirectedEdge @@ Reverse[e], UndirectedEdge @@ e})

edgeQ[g, {1, 2}]


If the ordering is important, remove DirectedEdge @@ Reverse[e] from the function definition.

Notes: As @Szabolcs noted in the comments, a <-> b is equivalent to UndirectedEdge, but a -> b is not the same as DirectedEdge. a -> b is treated as DirectedEdge only in a directed graph; in an undirected or mixed graph it is treated as UndirectedEdge.

  • $\begingroup$ It would be good to mention the non-obvious property that UndirectedEdge[a,b] (same as a <-> b) tests for an undirected edge only (but not directed), DirectedEdge[a,b] tests for a directed edge only (but not undirected) and Rule[a, b] (same as a -> b and different from DirectedEdge[a,b]) test for either/both. This is important when it is not known beforehand if the graph is directed or if working with mixed graphs. Oh, and this important property is of course not documented ... $\endgroup$
    – Szabolcs
    May 1, 2016 at 13:50
  • $\begingroup$ The way the answer is phrased now seems to imply that -> represents a directed edge but it doesn't ... it could also be undirected. $\endgroup$
    – Szabolcs
    May 1, 2016 at 13:51
  • 1
    $\begingroup$ Hm, actually I was wrong and it turns out that in mixed graphs -> is interpreted as strictly undirected. In directed ones it's interpreted as directed and in undirected ones it's interpreted as undirected. $\endgroup$
    – Szabolcs
    May 1, 2016 at 13:53
  • $\begingroup$ @Szabolcs, good points, I added a note covering your observations. $\endgroup$
    – kglr
    May 1, 2016 at 14:01
  • $\begingroup$ @Szabolcs, thank you for the edit. (I still use version 9, so could not use a mixed graph to check how it works with different forms of the second argument.) $\endgroup$
    – kglr
    May 1, 2016 at 14:09

Your Answer

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

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