# Section1.4Fiddling with Vertices and Edges

Although we can get a lot done with the graphs already in Sage, most of the time we will need to construct our own. The simplest approach is to modify one of the prebuilt graphs.

For an example, we start with the circulant graph $G$ on 9 vertices with connection set $C=\{1,2,7,8\}$. So $V(G)=\mathbb{Z}_9$ and vertices $i$ and $j$ are adjacent if their difference is in $C$.

For later use we also make a copy of $G$:

You can use G.show() to get a view of your graph, this can provide a useful check.

We find the neighbors of 0:

and attempt to confirm that $(0,1)$ is an edge by

and then realize that we should have tried

or

The last alternative is recommended. We can delete this edge:

and confirm the effect by

Note that G.delete_edge() alters $G$ in place, which is why I prepared a copy of it. The copy is unaltered:

Deleting an edge that is not present has no effect. We can delete the members of a list of edges with

Similarly we can add an edge or list of edges—type G.add followed by tab to see the things we can add and G.delete followed by tab for the things we can delete (which of course include vertices and list of vertices).

Adding a vertex increases the vertex set but, naturally enough, does not add any edges. If $S$ is a list of vertices of $G$, we can add a new vertex adjacent to each vertex in $S$ as follows.

Here the argument [ (10,s) for s in S ] to G.add_edges() is a simple example of a list comprehension. We will find these are very useful.

Edge contraction is one basic operation in graph theory that is not built into Sage. The following procedure identifies two vertices in a graph.

A useful generalization would be a procedure that took a graph $G$ and a partition of its vertex set as its input, and returned a graph with the cells of the partition as vertices and where two cells are adjacent if there is an edge that joins a vertex in the first cell to a vertex in the second.