networkx.MultiGraph.subgraph

MultiGraph.subgraph(nbunch)[source]

Return a SubGraph view of the subgraph induced on nodes in nbunch.

The induced subgraph of the graph contains the nodes in nbunch and the edges between those nodes.

Parameters:nbunch (list, iterable) – A container of nodes which will be iterated through once.
Returns:G – A subgraph of the graph with the same edge attributes.
Return type:Graph

Notes

The graph, edge, and node attributes in the returned subgraph view are references to the corresponding attributes in the original graph. The view is read-only.

To create a full graph version of the subgraph with its own copy of the edge or node attributes, use:

>>> G.edge_subgraph(edges).copy()  

For an inplace reduction of a graph to a subgraph you can remove nodes: G.remove_nodes_from([n for n in G if n not in set(nbunch)])

Examples

>>> G = nx.Graph()   # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> nx.add_path(G, [0, 1, 2, 3])
>>> H = G.subgraph([0, 1, 2])
>>> list(H.edges)
[(0, 1), (1, 2)]