2

Using networkx I created a graph G and added the edge (1,2). Strangely,

(1,2) in G.edges() == False

but

G.has_edge(1,2) == True

I'm baffled. This is a concise summary of the problem. The actual graph data is large and cannot be reproduced here in full.

antianticamper
  • 305
  • 1
  • 3
  • 8

1 Answers1

2

The issue is that G.edges() only has each edge once. Since it's an undirected graph, it could be as either (1,2) or as (2,1) (you wouldn't want both to appear --- you might be iterating and delete the edge the first time). You can't be sure of what order it will do so because it's coming from a python dict, which does not have predictable order. You could do (1,2) in G.edges() or (2,1) in G.edges(), but you really don't want to do that - it's inefficient to create the edge lists.

So the test should use G.has_edge(1,2) which checks it correctly (and much more efficiently).


Just to show the lack of predictability for different python implementations, this is what I get

In [3]: G=nx.Graph()

In [4]: G.add_edge(1,2)

In [5]: G.edges()

Out[5]: [(1, 2)]

In [6]: (1,2) in G.edges()

Out[6]: True

In [7]: G.add_edge(4,3)

In [8]: G.edges()

Out[8]: [(1, 2), (3, 4)]

In [9]: (4,3) in G.edges()

Out[9]: False

Community
  • 1
  • 1
Joel
  • 22,598
  • 6
  • 69
  • 93