Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need to add either a vertex or an edge to a graph, and also sometimes, vertices or edges, or a mixture of the two. How to write a function for this?

share|improve this question

The functions you need are VertexAdd, EdgeAdd, and their relatives VertexDelete and EdgeDelete.

For the graph

 g = Graph[{a, b, c}, {a \[UndirectedEdge] b, b \[UndirectedEdge] c, 
 c \[UndirectedEdge] a}]

graph g

Adding a vertex

  VertexAdd[g, "d"]


add a vertex

Adding an edge

 EdgeAdd[g, d \[UndirectedEdge] a]


add edge

Deleting an edge

 EdgeDelete[g, c \[UndirectedEdge] a]


delete and edge

share|improve this answer
Can I add a mixture list of vertices and edges to an existing graph? How to write such a function addToGraph[g, {4, 1 \[UndirectedEdge] 2}] which will add another vertex 4 and an edge between 1 and 2? Thank you. – Qiang Li Feb 17 '12 at 23:16
I don't know of a built-in function that does that. But, it seems straightforward to do define a composite function that does both: addToGraph[g_, newvertices_List, newedges_List]:= (VertexAdd[g,newvertices];EdgeAdd[g,newedges];). Use it as h=addToGraph[g,{d,e},{a->d,a->e}] to add two new vertices and two new edges to graph g to get a new graph h. – kglr Feb 17 '12 at 23:35
I guess I wanted to know what if I mixed the newvertices_List and newedges_List in a single list? – Qiang Li Feb 18 '12 at 0:20
@QiangLi, you need modify slightly to parse the new stuff into vertex and edge parts. For example, let newstuff = {a, a \[UndirectedEdge] b, b \[UndirectedEdge] e, d, b}. Then, you can use newedges=Cases[newstuff, _ \[UndirectedEdge] _]; newvertices = Complement[newstuff, newedges] as the first two steps of the composite function on the right hand side. That is, the function becomes `addToGraph2[g_, newstuff_]:=(newedges=Cases[newstuff, _ \ [UndirectedEdge] _]; newvertices = Complement[newstuff, newedges]; VertexAdd[g,newvertices];EdgeAdd[g,newedges];). – kglr Feb 18 '12 at 0:52
@QiangLi, you could create a new Graph with the new vertices and edges, and then use GraphUnion. – becko May 20 '12 at 16:17

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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