Removing self-loops from undirected networkx graph

The previous method will be deprecated: use nx.selfloop_edges() instead


The selfloop methods were deprecated as graph methods in favor of networkx functions in version 2.0.

version 1.x:

G.remove_edges_from(G.selfloop_edges())

version 2.x:

G.remove_edges_from(nx.selfloop_edges(G))

The method remove_edge does what you need. Simply filter for when the edge source and destination are the same:

for u, v in G.edges_iter():
    if u == v: 
        G.remove_edge(u,v)

(instructions for networkx 1.x below)

If you're using networkx 2.x try

G.remove_edges_from(nx.selfloop_edges(G))

If you have a MultiGraph (which for example configuration_model produces), this may not work if you have an older release of 2.x with a minor bug. If so and you don't want to upgrade, then you need to convert this into a list before removing edges.

G.remove_edges_from(list(nx.selfloop_edges(G)))

This bug has been corrected https://github.com/networkx/networkx/issues/4068.


In version 1.x (when I originally answered this question), it was:

G.remove_edges_from(G.selfloop_edges())