0

With networkx2 does the .nodes() method guarantee some kind of consistent node ordering, or can we expect the ordering to change between multiple calls on the same graph?

Carlos G. Oliver
  • 315
  • 4
  • 14

1 Answers1

1

Up to Python 3.6

The nodes are kept in a dictionary, and nodes() return a list of the dictionary keys. The order will be constant as long as you don't change anything in the graph nodes. Adding/removing nodes or edges might effect the order.

From Python 3.6:

In some Python implementations, like CPython, dictionary maintain the insertion order, which mean you can expect the print order, however not all of them

From Python 3.7:

Ordered dictionary is now language standard.

From the docs

def nodes(self): 
    """Return a copy of the graph nodes in a list.""" 
    return self.adj.keys()

networkx support Python 2.7, 3.4, 3.5, or 3.6, the behavior depends on your version.

Guy
  • 46,488
  • 10
  • 44
  • 88
  • Thanks! but as far as I know, dictionary keys don't guarantee a constant ordering? I may be wrong since I think this changed in python 3.6. Actually, according to (https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6) since 3.7 insertion order is guaranteed. Thanks! – Carlos G. Oliver Mar 25 '19 at 13:03
  • 1
    @CarlosG.Oliver Updated my answer. – Guy Mar 25 '19 at 13:21
  • Isn't it since 3.7 rather than since 3.6 that the change was made? – Joel Mar 26 '19 at 01:04
  • @Joel It wasn't part of the language yet, only part of some implementations, namely CPython which is the common implementation. I will update the answer accordingly. – Guy Mar 26 '19 at 05:15