G.add_node(1) # add a single nodeG.add_nodes_from([2, 3]) # add nodes from an iterableG.add_nodes_from([(4, {"color": "red"}), (5, {"color": "green"})]) # add nodes with node attributes# add nodes from another graphH = nx.path_graph(10)G.add_nodes_from(H)
Edges
G.add_edge(1, 2) # add a single edgeG.add_edges_from([(1, 2), (1, 3)]) # Add a list of edges# add edges from another graphH = nx.path_graph(10)G.add_edges_from(H.edges)
Examining Elements
G.number_of_nodes()G.number_of_edges()list(G.nodes) # list of nodeslist(G.edges) # list of edges# the adjacency objects (deges) of the nodeG.adj[1]G.neighbors(1)# Set and get the edge attributesG[1][2]['color'] = "blue"G[1][2]G.edges[1, 2]# the degree of the nodeG.degree[1]
Removing Elements
G.remove_node(2) # remove the nodeG.remove_nodes_from([1, 2]) # removes the nodes and all adjacent edges.G.remove_edge(1, 3) G.remove_edges_from([(1, 2), (2, 3)]) # remove the edges
Graph Constructors
H = nx.DiGraph(G) # create a directed-graph using another graphedgelist = [(0, 1), (1, 2), (2, 3)]H = nx.Graph(edgelist) # create a graph from an edge listadjacency_dict = {0: (1, 2), 1: (0, 2), 2: (0, 1)}H = nx.Graph(adjacency_dict) # create a graph using adjacency dictionary