disjoint_union#

disjoint_union(G, H)[source]#

Combine graphs G and H. The nodes are assumed to be unique (disjoint).

This algorithm automatically relabels nodes to avoid name collisions.

Parameters:
G,Hgraph

A NetworkX graph

Returns:
UA union graph with the same type as G.

Notes

A new graph is created, of the same class as G. It is recommended that G and H be either both directed or both undirected.

The nodes of G are relabeled 0 to len(G)-1, and the nodes of H are relabeled len(G) to len(G)+len(H)-1.

Renumbering forces G and H to be disjoint, so no exception is ever raised for a name collision. To preserve the check for common nodes, use union().

Edge and node attributes are propagated from G and H to the union graph. Graph attributes are also propagated, but if they are present in both G and H, then the value from H is used.

To combine graphs that have common nodes, consider compose(G, H) or the method, Graph.update().

Examples

>>> G = nx.Graph([(0, 1), (0, 2), (1, 2)])
>>> H = nx.Graph([(0, 3), (1, 2), (2, 3)])
>>> G.nodes[0]["key1"] = 5
>>> H.nodes[0]["key2"] = 10
>>> U = nx.disjoint_union(G, H)
>>> U.nodes(data=True)
NodeDataView({0: {'key1': 5}, 1: {}, 2: {}, 3: {'key2': 10}, 4: {}, 5: {}, 6: {}})
>>> U.edges
EdgeView([(0, 1), (0, 2), (1, 2), (3, 4), (4, 6), (5, 6)])
----

Additional backends implement this function

graphblas : OpenMP-enabled sparse linear algebra backend.