0% found this document useful (0 votes)
242 views853 pages

Networkx Reference

This document is a reference manual for NetworkX, an open source Python software package for complex network analysis and graph theory. It provides overviews of the basic concepts and capabilities of NetworkX, including graph types and classes, algorithms for graph analysis, and functions for graph creation, reporting and drawing. The document contains detailed documentation on NetworkX's graph types, algorithm implementations, and capabilities for tasks like community detection, centrality measures, shortest paths, and more.

Uploaded by

SWAPNIL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
242 views853 pages

Networkx Reference

This document is a reference manual for NetworkX, an open source Python software package for complex network analysis and graph theory. It provides overviews of the basic concepts and capabilities of NetworkX, including graph types and classes, algorithms for graph analysis, and functions for graph creation, reporting and drawing. The document contains detailed documentation on NetworkX's graph types, algorithm implementations, and capabilities for tasks like community detection, centrality measures, shortest paths, and more.

Uploaded by

SWAPNIL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

NetworkX Reference

Release 2.5

Aric Hagberg, Dan Schult, Pieter Swart

Aug 22, 2020


CONTENTS

1 Introduction 1
1.1 NetworkX Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Graph Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Graph Reporting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.5 Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.6 Drawing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.7 Data Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2 Graph types 7
2.1 Which graph class should I use? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2 Basic graph types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.3 Graph Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
2.4 Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

3 Algorithms 141
3.1 Approximations and Heuristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
3.2 Assortativity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
3.3 Asteroidal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
3.4 Bipartite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
3.5 Boundary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
3.6 Bridges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
3.7 Centrality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
3.8 Chains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
3.9 Chordal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
3.10 Clique . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
3.11 Clustering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
3.12 Coloring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
3.13 Communicability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
3.14 Communities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
3.15 Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
3.16 Connectivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
3.17 Cores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
3.18 Covering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
3.19 Cycles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
3.20 Cuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
3.21 D-Separation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
3.22 Directed Acyclic Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
3.23 Distance Measures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
3.24 Distance-Regular Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348

i
3.25 Dominance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
3.26 Dominating Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
3.27 Efficiency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
3.28 Eulerian . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
3.29 Flows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
3.30 Graph Hashing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
3.31 Graphical degree sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
3.32 Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
3.33 Hybrid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
3.34 Isolates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
3.35 Isomorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
3.36 Link Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
3.37 Link Prediction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
3.38 Lowest Common Ancestor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
3.39 Matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
3.40 Minors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
3.41 Maximal independent set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
3.42 non-randomness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
3.43 Moral . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
3.44 Node Classification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
3.45 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
3.46 Planarity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
3.47 Planar Drawing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
3.48 Reciprocity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
3.49 Regular . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
3.50 Rich Club . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
3.51 Shortest Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
3.52 Similarity Measures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
3.53 Simple Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
3.54 Small-world . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
3.55 s metric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
3.56 Sparsifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
3.57 Structural holes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
3.58 Swap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
3.59 Threshold Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
3.60 Tournament . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
3.61 Traversal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
3.62 Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
3.63 Triads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
3.64 Vitality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
3.65 Voronoi cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
3.66 Wiener index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564

4 Functions 567
4.1 Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
4.2 Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
4.3 Edges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
4.4 Self loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
4.5 Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
4.6 Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
4.7 Freezing graph structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585

5 Graph generators 587


5.1 Atlas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587

ii
5.2 Classic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
5.3 Expanders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597
5.4 Lattice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599
5.5 Small . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602
5.6 Random Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606
5.7 Duplication Divergence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618
5.8 Degree Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619
5.9 Random Clustered . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
5.10 Directed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
5.11 Geometric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
5.12 Line Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638
5.13 Ego Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641
5.14 Stochastic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641
5.15 AS graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642
5.16 Intersection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643
5.17 Social Networks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644
5.18 Community . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645
5.19 Spectral . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655
5.20 Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656
5.21 Non Isomorphic Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658
5.22 Triads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659
5.23 Joint Degree Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 660
5.24 Mycielski . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663
5.25 Harary Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 664
5.26 Cographs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666
5.27 Interval Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667
5.28 Sudoku . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667

6 Linear algebra 671


6.1 Graph Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671
6.2 Laplacian Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 673
6.3 Bethe Hessian Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 676
6.4 Algebraic Connectivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677
6.5 Attribute Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680
6.6 Modularity Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 684
6.7 Spectrum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686

7 Converting to and from other data formats 689


7.1 To NetworkX Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689
7.2 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 690
7.3 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691
7.4 Numpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692
7.5 Scipy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 700
7.6 Pandas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 702

8 Relabeling nodes 709


8.1 Relabeling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 709

9 Reading and writing graphs 713


9.1 Adjacency List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 713
9.2 Multiline Adjacency List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 717
9.3 Edge List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 720
9.4 GEXF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 726
9.5 GML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 729
9.6 Pickle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 734

iii
9.7 GraphML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 736
9.8 JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 740
9.9 LEDA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 746
9.10 YAML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 747
9.11 SparseGraph6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 748
9.12 Pajek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 755
9.13 GIS Shapefile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757

10 Drawing 759
10.1 Matplotlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759
10.2 Graphviz AGraph (dot) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 769
10.3 Graphviz with pydot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 772
10.4 Graph Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 775

11 Randomness 785

12 Exceptions 787
12.1 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787

13 Utilities 789
13.1 Helper Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
13.2 Data Structures and Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 791
13.3 Random Sequence Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 792
13.4 Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 793
13.5 Cuthill-Mckee Ordering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 797

14 Glossary 801

A Tutorial 803
A.1 Creating a graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803
A.2 Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803
A.3 Edges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 804
A.4 Examining elements of a graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805
A.5 Removing elements from a graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805
A.6 Using the graph constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 806
A.7 What to use as nodes and edges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 806
A.8 Accessing edges and neighbors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 806
A.9 Adding attributes to graphs, nodes, and edges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 807
A.10 Directed graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 808
A.11 Multigraphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 808
A.12 Graph generators and graph operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809
A.13 Analyzing graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 810
A.14 Drawing graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 811

Bibliography 815

Python Module Index 817

Index 821

iv
CHAPTER

ONE

INTRODUCTION

The structure of NetworkX can be seen by the organization of its source code. The package provides classes for graph
objects, generators to create standard graphs, IO routines for reading in existing datasets, algorithms to analyze the
resulting networks and some basic drawing tools.
Most of the NetworkX API is provided by functions which take a graph object as an argument. Methods of the graph
object are limited to basic manipulation and reporting. This provides modularity of code and documentation. It also
makes it easier for newcomers to learn about the package in stages. The source code for each module is meant to be
easy to read and reading this Python code is actually a good way to learn more about network algorithms, but we have
put a lot of effort into making the documentation sufficient and friendly. If you have suggestions or questions please
contact us by joining the NetworkX Google group.
Classes are named using CamelCase (capital letters at the start of each word). functions, methods and variable
names are lower_case_underscore (lowercase with an underscore representing a space between words).

1.1 NetworkX Basics

After starting Python, import the networkx module with (the recommended way)

>>> import networkx as nx

To save repetition, in the documentation we assume that NetworkX has been imported this way.
If importing networkx fails, it means that Python cannot find the installed module. Check your installation and your
PYTHONPATH.
The following basic graph types are provided as Python classes:
Graph This class implements an undirected graph. It ignores multiple edges between two nodes. It does allow
self-loop edges between a node and itself.
DiGraph Directed graphs, that is, graphs with directed edges. Provides operations common to directed graphs, (a
subclass of Graph).
MultiGraph A flexible graph class that allows multiple undirected edges between pairs of nodes. The additional
flexibility leads to some degradation in performance, though usually not significant.
MultiDiGraph A directed version of a MultiGraph.
Empty graph-like objects are created with

>>> G = [Link]()
>>> G = [Link]()
>>> G = [Link]()
>>> G = [Link]()

1
NetworkX Reference, Release 2.5

All graph classes allow any hashable object as a node. Hashable objects include strings, tuples, integers, and more.
Arbitrary edge attributes such as weights and labels can be associated with an edge.
The graph internal data structures are based on an adjacency list representation and implemented using Python dictio-
nary datastructures. The graph adjacency structure is implemented as a Python dictionary of dictionaries; the outer
dictionary is keyed by nodes to values that are themselves dictionaries keyed by neighboring node to the edge at-
tributes associated with that edge. This “dict-of-dicts” structure allows fast addition, deletion, and lookup of nodes
and neighbors in large graphs. The underlying datastructure is accessed directly by methods (the programming in-
terface “API”) in the class definitions. All functions, on the other hand, manipulate graph-like objects solely via
those API methods and not by acting directly on the datastructure. This design allows for possible replacement of the
‘dicts-of-dicts’-based datastructure with an alternative datastructure that implements the same methods.

1.2 Graphs

The first choice to be made when using NetworkX is what type of graph object to use. A graph (network) is a collection
of nodes together with a collection of edges that are pairs of nodes. Attributes are often associated with nodes and/or
edges. NetworkX graph objects come in different flavors depending on two main properties of the network:
• Directed: Are the edges directed? Does the order of the edge pairs (𝑢, 𝑣) matter? A directed graph is specified
by the “Di” prefix in the class name, e.g. DiGraph(). We make this distinction because many classical graph
properties are defined differently for directed graphs.
• Multi-edges: Are multiple edges allowed between each pair of nodes? As you might imagine, multiple edges
requires a different data structure, though clever users could design edge data attributes to support this function-
ality. We provide a standard data structure and interface for this type of graph using the prefix “Multi”, e.g.,
MultiGraph().
The basic graph classes are named: Graph, DiGraph, MultiGraph, and MultiDiGraph

1.2.1 Nodes and Edges

The next choice you have to make when specifying a graph is what kinds of nodes and edges to use.
If the topology of the network is all you care about then using integers or strings as the nodes makes sense and you
need not worry about edge data. If you have a data structure already in place to describe nodes you can simply use
that structure as your nodes provided it is hashable. If it is not hashable you can use a unique identifier to represent
the node and assign the data as a node attribute.
Edges often have data associated with them. Arbitrary data can be associated with edges as an edge attribute. If the
data is numeric and the intent is to represent a weighted graph then use the ‘weight’ keyword for the attribute. Some
of the graph algorithms, such as Dijkstra’s shortest path algorithm, use this attribute name by default to get the weight
for each edge.
Attributes can be assigned to an edge by using keyword/value pairs when adding edges. You can use any keyword to
name your attribute and can then query the edge data using that attribute keyword.
Once you’ve decided how to encode the nodes and edges, and whether you have an undirected/directed graph with or
without multiedges you are ready to build your network.

2 Chapter 1. Introduction
NetworkX Reference, Release 2.5

1.3 Graph Creation

NetworkX graph objects can be created in one of three ways:


• Graph generators—standard algorithms to create network topologies.
• Importing data from pre-existing (usually file) sources.
• Adding edges and nodes explicitly.
Explicit addition and removal of nodes/edges is the easiest to describe. Each graph object supplies methods to manip-
ulate the graph. For example,

>>> import networkx as nx


>>> G = [Link]()
>>> G.add_edge(1, 2) # default edge data=1
>>> G.add_edge(2, 3, weight=0.9) # specify edge data

Edge attributes can be anything:

>>> import math


>>> G.add_edge('y', 'x', function=[Link])
>>> G.add_node([Link]) # any hashable can be a node

You can add many edges at one time:

>>> elist = [(1, 2), (2, 3), (1, 4), (4, 2)]
>>> G.add_edges_from(elist)
>>> elist = [('a', 'b', 5.0), ('b', 'c', 3.0), ('a', 'c', 1.0), ('c', 'd', 7.3)]
>>> G.add_weighted_edges_from(elist)

See the Tutorial for more examples.


Some basic graph operations such as union and intersection are described in the operators module documentation.
Graph generators such as binomial_graph() and erdos_renyi_graph() are provided in the graph genera-
tors subpackage.
For importing network data from formats such as GML, GraphML, edge list text files see the reading and writing
graphs subpackage.

1.4 Graph Reporting

Class views provide basic reporting of nodes, neighbors, edges and degree. These views provide iteration over the
properties as well as membership queries and data attribute lookup. The views refer to the graph data structure so
changes to the graph are reflected in the views. This is analogous to dictionary views in Python 3. If you want to
change the graph while iterating you will need to use e.g. for e in list([Link]):. The views provide
set-like operations, e.g. union and intersection, as well as dict-like lookup and iteration of the data attributes us-
ing [Link][u, v]['color'] and for e, datadict in [Link]():. Methods [Link].
items() and [Link]() are familiar from python dicts. In addition [Link]() provides
specific attribute iteration e.g. for e, e_color in [Link]('color'):.
The basic graph relationship of an edge can be obtained in two ways. One can look for neighbors of a node or one can
look for edges. We jokingly refer to people who focus on nodes/neighbors as node-centric and people who focus on
edges as edge-centric. The designers of NetworkX tend to be node-centric and view edges as a relationship between
nodes. You can see this by our choice of lookup notation like G[u] providing neighbors (adjacency) while edge
lookup is [Link][u, v]. Most data structures for sparse graphs are essentially adjacency lists and so fit this

1.3. Graph Creation 3


NetworkX Reference, Release 2.5

perspective. In the end, of course, it doesn’t really matter which way you examine the graph. [Link] removes
duplicate representations of undirected edges while neighbor reporting across all nodes will naturally report both
directions.
Any properties that are more complicated than edges, neighbors and degree are provided by functions. For exam-
ple [Link](G, n) gives the number of triangles which include node n as a vertex. These functions are
grouped in the code and documentation under the term algorithms.

1.5 Algorithms

A number of graph algorithms are provided with NetworkX. These include shortest path, and breadth first search (see
traversal), clustering and isomorphism algorithms and others. There are many that we have not developed yet too. If
you implement a graph algorithm that might be useful for others please let us know through the NetworkX Google
group or the Github Developer Zone.
As an example here is code to use Dijkstra’s algorithm to find the shortest weighted path:

>>> G = [Link]()
>>> e = [('a', 'b', 0.3), ('b', 'c', 0.9), ('a', 'c', 0.5), ('c', 'd', 1.2)]
>>> G.add_weighted_edges_from(e)
>>> print(nx.dijkstra_path(G, 'a', 'd'))
['a', 'c', 'd']

1.6 Drawing

While NetworkX is not designed as a network drawing tool, we provide a simple interface to drawing packages
and some simple layout algorithms. We interface to the excellent Graphviz layout tools like dot and neato with the
(suggested) pygraphviz package or the pydot interface. Drawing can be done using external programs or the Matplotlib
Python package. Interactive GUI interfaces are possible, though not provided. The drawing tools are provided in the
module drawing.
The basic drawing functions essentially place the nodes on a scatterplot using the positions you provide via a dictionary
or the positions are computed with a layout function. The edges are lines between those dots.

>>> import [Link] as plt


>>> G = nx.cubical_graph()
>>> [Link](121)
<[Link]._subplots.AxesSubplot object at ...>
>>> [Link](G) # default spring_layout
>>> [Link](122)
<[Link]._subplots.AxesSubplot object at ...>
>>> [Link](G, pos=nx.circular_layout(G), node_color='r', edge_color='b')

4 Chapter 1. Introduction
NetworkX Reference, Release 2.5

See the examples for more ideas.

1.7 Data Structure

NetworkX uses a “dictionary of dictionaries of dictionaries” as the basic network data structure. This allows fast
lookup with reasonable storage for large sparse networks. The keys are nodes so G[u] returns an adjacency dictionary
keyed by neighbor to the edge attribute dictionary. A view of the adjacency data structure is provided by the dict-like
object [Link] as e.g. for node, nbrsdict in [Link]():. The expression G[u][v] returns the
edge attribute dictionary itself. A dictionary of lists would have also been possible, but not allow fast edge detection
nor convenient storage of edge data.
Advantages of dict-of-dicts-of-dicts data structure:
• Find edges and remove edges with two dictionary look-ups.
• Prefer to “lists” because of fast lookup with sparse storage.
• Prefer to “sets” since data can be attached to edge.
• G[u][v] returns the edge attribute dictionary.
• n in G tests if node n is in graph G.
• for n in G: iterates through the graph.
• for nbr in G[n]: iterates through neighbors.

1.7. Data Structure 5


NetworkX Reference, Release 2.5

As an example, here is a representation of an undirected graph with the edges (𝐴, 𝐵) and (𝐵, 𝐶).

>>> G = [Link]()
>>> G.add_edge('A', 'B')
>>> G.add_edge('B', 'C')
>>> print([Link])
{'A': {'B': {}}, 'B': {'A': {}, 'C': {}}, 'C': {'B': {}}}

The data structure gets morphed slightly for each base graph class. For DiGraph two dict-of-dicts-of-dicts structures
are provided, one for successors ([Link]) and one for predecessors ([Link]). For MultiGraph/MultiDiGraph
we use a dict-of-dicts-of-dicts-of-dicts1 where the third dictionary is keyed by an edge key identifier to the fourth
dictionary which contains the edge attributes for that edge between the two nodes.
Graphs provide two interfaces to the edge data attributes: adjacency and edges. So G[u][v]['width'] is the same
as [Link][u, v]['width'].

>>> G = [Link]()
>>> G.add_edge(1, 2, color='red', weight=0.84, size=300)
>>> print(G[1][2]['size'])
300
>>> print([Link][1, 2]['color'])
red

• ;
• ;
• .

1 “It’s dictionaries all the way down.”

6 Chapter 1. Introduction
CHAPTER

TWO

GRAPH TYPES

NetworkX provides data structures and methods for storing graphs.


All NetworkX graph classes allow (hashable) Python objects as nodes and any Python object can be assigned as an
edge attribute.
The choice of graph class depends on the structure of the graph you want to represent.

2.1 Which graph class should I use?

Networkx Class Type Self-loops allowed Parallel edges allowed


Graph undirected Yes No
DiGraph directed Yes No
MultiGraph undirected Yes Yes
MultiDiGraph directed Yes Yes

2.2 Basic graph types

2.2.1 Graph—Undirected graphs with self loops

Overview

class Graph(incoming_graph_data=None, **attr)


Base class for undirected graphs.
A Graph stores nodes and edges with optional data, or attributes.
Graphs hold undirected edges. Self loops are allowed but multiple (parallel) edges are not.
Nodes can be arbitrary (hashable) Python objects with optional key/value attributes. By convention None is not
used as a node.
Edges are represented as links between nodes with optional key/value attributes.
Parameters
• incoming_graph_data (input graph (optional, default: None)) – Data to initialize graph. If
None (default) an empty graph is created. The data can be any format that is supported by
the to_networkx_graph() function, currently including edge list, dict of dicts, dict of lists,
NetworkX graph, NumPy matrix or 2d ndarray, SciPy sparse matrix, or PyGraphviz graph.

7
NetworkX Reference, Release 2.5

• attr (keyword arguments, optional (default= no attributes)) – Attributes to add to graph as


key=value pairs.
See also:
DiGraph, MultiGraph, MultiDiGraph, OrderedGraph

Examples

Create an empty graph structure (a “null graph”) with no nodes and no edges.

>>> G = [Link]()

G can be grown in several ways.


Nodes:
Add one node at a time:

>>> G.add_node(1)

Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph).

>>> G.add_nodes_from([2, 3])


>>> G.add_nodes_from(range(100, 110))
>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)

In addition to strings and integers any hashable Python object (except None) can represent a node, e.g. a
customized node object, or even another Graph.

>>> G.add_node(H)

Edges:
G can also be grown by adding edges.
Add one edge,

>>> G.add_edge(1, 2)

a list of edges,

>>> G.add_edges_from([(1, 2), (1, 3)])

or a collection of edges,

>>> G.add_edges_from([Link])

If some edges connect nodes not yet in the graph, the nodes are added automatically. There are no errors when
adding nodes or edges that already exist.
Attributes:
Each graph, node, and edge can hold key/value attribute pairs in an associated attribute dictionary (the keys
must be hashable). By default these are empty, but can be added or changed using add_edge, add_node or direct
manipulation of the attribute dictionaries named graph, node and edge respectively.

8 Chapter 2. Graph types


NetworkX Reference, Release 2.5

>>> G = [Link](day="Friday")
>>> [Link]
{'day': 'Friday'}

Add node attributes using add_node(), add_nodes_from() or [Link]


>>> G.add_node(1, time="5pm")
>>> G.add_nodes_from([3], time="2pm")
>>> [Link][1]
{'time': '5pm'}
>>> [Link][1]["room"] = 714 # node must exist already to use [Link]
>>> del [Link][1]["room"] # remove attribute
>>> list([Link](data=True))
[(1, {'time': '5pm'}), (3, {'time': '2pm'})]

Add edge attributes using add_edge(), add_edges_from(), subscript notation, or [Link].


>>> G.add_edge(1, 2, weight=4.7)
>>> G.add_edges_from([(3, 4), (4, 5)], color="red")
>>> G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
>>> G[1][2]["weight"] = 4.7
>>> [Link][1, 2]["weight"] = 4

Warning: we protect the graph data structure by making [Link] a read-only dict-like structure. However, you
can assign to attributes in e.g. [Link][1, 2]. Thus, use 2 sets of brackets to add/change data attributes:
[Link][1, 2]['weight'] = 4 (For multigraphs: [Link][u, v, key][name] = value).
Shortcuts:
Many common graph features allow python syntax to speed reporting.
>>> 1 in G # check if node in graph
True
>>> [n for n in G if n < 3] # iterate through nodes
[1, 2]
>>> len(G) # number of nodes in graph
5

Often the best way to traverse all edges of a graph is via the neighbors. The neighbors are reported as an
adjacency-dict [Link] or [Link]()
>>> for n, nbrsdict in [Link]():
... for nbr, eattr in [Link]():
... if "weight" in eattr:
... # Do something useful with the edges
... pass

But the edges() method is often more convenient:


>>> for u, v, weight in [Link]("weight"):
... if weight is not None:
... # Do something useful with the edges
... pass

Reporting:
Simple graph information is obtained using object-attributes and methods. Reporting typically provides views
instead of containers to reduce memory usage. The views update as the graph is updated similarly to dict-
views. The objects nodes, edges and adj provide access to data attributes via lookup (e.g. nodes[n],

2.2. Basic graph types 9


NetworkX Reference, Release 2.5

edges[u, v], adj[u][v]) and iteration (e.g. [Link](), [Link]('color'), nodes.


data('color', default='blue') and similarly for edges) Views exist for nodes, edges,
neighbors()/adj and degree.
For details on these and other miscellaneous methods, see below.
Subclasses (Advanced):
The Graph class uses a dict-of-dict-of-dict data structure. The outer dict (node_dict) holds adjacency information
keyed by node. The next dict (adjlist_dict) represents the adjacency information and holds edge data keyed by
neighbor. The inner dict (edge_attr_dict) represents the edge data and holds edge attribute values keyed by
attribute names.
Each of these three dicts can be replaced in a subclass by a user defined dict-like object. In general, the
dict-like features should be maintained but extra features can be added. To replace one of the dicts create
a new graph class by changing the class(!) variable holding the factory for that dict-like structure. The vari-
able names are node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory, adjlist_outer_dict_factory,
edge_attr_dict_factory and graph_attr_dict_factory.
node_dict_factory [function, (default: dict)] Factory function to be used to create the dict containing node
attributes, keyed by node id. It should require no arguments and return a dict-like object
node_attr_dict_factory: function, (default: dict) Factory function to be used to create the node attribute dict
which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like
object
adjlist_outer_dict_factory [function, (default: dict)] Factory function to be used to create the outer-most dict
in the data structure that holds adjacency info keyed by node. It should require no arguments and return a
dict-like object.
adjlist_inner_dict_factory [function, (default: dict)] Factory function to be used to create the adjacency list
dict which holds edge data keyed by neighbor. It should require no arguments and return a dict-like object
edge_attr_dict_factory [function, (default: dict)] Factory function to be used to create the edge attribute dict
which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like
object.
graph_attr_dict_factory [function, (default: dict)] Factory function to be used to create the graph attribute
dict which holds attribute values keyed by attribute name. It should require no arguments and return a
dict-like object.
Typically, if your extension doesn’t impact the data structure all methods will inherit without issue except:
to_directed/to_undirected. By default these methods create a DiGraph/Graph class and you probably
want them to create your extension of a DiGraph/Graph. To facilitate this we define two class variables that you
can set in your subclass.
to_directed_class [callable, (default: DiGraph or MultiDiGraph)] Class to create a new graph structure in the
to_directed method. If None, a NetworkX class (DiGraph or MultiDiGraph) is used.
to_undirected_class [callable, (default: Graph or MultiGraph)] Class to create a new graph structure in the
to_undirected method. If None, a NetworkX class (Graph or MultiGraph) is used.

10 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Examples

Create a low memory graph class that effectively disallows edge attributes by using a single attribute dict for all
edges. This reduces the memory used, but you lose edge attributes.

>>> class ThinGraph([Link]):


... all_edge_dict = {"weight": 1}
...
... def single_edge_dict(self):
... return self.all_edge_dict
...
... edge_attr_dict_factory = single_edge_dict
>>> G = ThinGraph()
>>> G.add_edge(2, 1)
>>> G[2][1]
{'weight': 1}
>>> G.add_edge(2, 2)
>>> G[2][1] is G[2][2]
True

Please see ordered for more examples of creating graph subclasses by overwriting the base class dict with
a dictionary-like object.

Methods

Adding and removing nodes and edges

Graph.__init__([incoming_graph_data]) Initialize a graph with edges, name, or graph attributes.


Graph.add_node(node_for_adding, **attr) Add a single node node_for_adding and update
node attributes.
Graph.add_nodes_from(nodes_for_adding, Add multiple nodes.
**attr)
Graph.remove_node(n) Remove node n.
Graph.remove_nodes_from(nodes) Remove multiple nodes.
Graph.add_edge(u_of_edge, v_of_edge, **attr) Add an edge between u and v.
Graph.add_edges_from(ebunch_to_add, **attr) Add all the edges in ebunch_to_add.
Graph.add_weighted_edges_from(ebunch_to_add) Add weighted edges in ebunch_to_add with speci-
fied weight attr
Graph.remove_edge(u, v) Remove the edge between u and v.
Graph.remove_edges_from(ebunch) Remove all edges specified in ebunch.
[Link]([edges, nodes]) Update the graph using nodes/edges/graphs as input.
[Link]() Remove all nodes and edges from the graph.
Graph.clear_edges() Remove all edges from the graph without altering
nodes.

2.2. Basic graph types 11


NetworkX Reference, Release 2.5

[Link].__init__

Graph.__init__(incoming_graph_data=None, **attr)
Initialize a graph with edges, name, or graph attributes.
Parameters
• incoming_graph_data (input graph (optional, default: None)) – Data to initialize graph. If
None (default) an empty graph is created. The data can be an edge list, or any NetworkX
graph object. If the corresponding optional Python packages are installed the data can also
be a NumPy matrix or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz graph.
• attr (keyword arguments, optional (default= no attributes)) – Attributes to add to graph as
key=value pairs.
See also:
convert()

Examples

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G = [Link](name="my graph")
>>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
>>> G = [Link](e)

Arbitrary graph attribute pairs (key=value) may be assigned

>>> G = [Link](e, day="Friday")


>>> [Link]
{'day': 'Friday'}

[Link].add_node

Graph.add_node(node_for_adding, **attr)
Add a single node node_for_adding and update node attributes.
Parameters
• node_for_adding (node) – A node can be any hashable Python object except None.
• attr (keyword arguments, optional) – Set or change node attributes using key=value.
See also:
add_nodes_from()

12 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Examples

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_node(1)
>>> G.add_node("Hello")
>>> K3 = [Link]([(0, 1), (1, 2), (2, 0)])
>>> G.add_node(K3)
>>> G.number_of_nodes()
3

Use keywords set/change node attributes:

>>> G.add_node(1, size=10)


>>> G.add_node(3, weight=0.4, UTM=("13S", 382871, 3972649))

Notes

A hashable object is one that can be used as a key in a Python dictionary. This includes strings, numbers, tuples
of strings and numbers, etc.
On many platforms hashable items also include mutables such as NetworkX Graphs, though one should be
careful that the hash doesn’t change on mutables.

[Link].add_nodes_from

Graph.add_nodes_from(nodes_for_adding, **attr)
Add multiple nodes.
Parameters
• nodes_for_adding (iterable container) – A container of nodes (list, dict, set, etc.). OR A
container of (node, attribute dict) tuples. Node attributes are updated using the attribute dict.
• attr (keyword arguments, optional (default= no attributes)) – Update attributes for all nodes
in nodes. Node attributes specified in nodes as a tuple take precedence over attributes spec-
ified via keyword arguments.
See also:
add_node()

Examples

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_nodes_from("Hello")
>>> K3 = [Link]([(0, 1), (1, 2), (2, 0)])
>>> G.add_nodes_from(K3)
>>> sorted([Link](), key=str)
[0, 1, 2, 'H', 'e', 'l', 'o']

Use keywords to update specific node attributes for every node.

>>> G.add_nodes_from([1, 2], size=10)


>>> G.add_nodes_from([3, 4], weight=0.4)

2.2. Basic graph types 13


NetworkX Reference, Release 2.5

Use (node, attrdict) tuples to update attributes for specific nodes.

>>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})])


>>> [Link][1]["size"]
11
>>> H = [Link]()
>>> H.add_nodes_from([Link](data=True))
>>> [Link][1]["size"]
11

[Link].remove_node

Graph.remove_node(n)
Remove node n.
Removes the node n and all adjacent edges. Attempting to remove a non-existent node will raise an exception.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
remove_nodes_from()

Examples

>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> list([Link])
[(0, 1), (1, 2)]
>>> G.remove_node(1)
>>> list([Link])
[]

[Link].remove_nodes_from

Graph.remove_nodes_from(nodes)
Remove multiple nodes.
Parameters nodes (iterable container) – A container of nodes (list, dict, set, etc.). If a node in the
container is not in the graph it is silently ignored.
See also:
remove_node()

14 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Examples

>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> e = list([Link])
>>> e
[0, 1, 2]
>>> G.remove_nodes_from(e)
>>> list([Link])
[]

[Link].add_edge

Graph.add_edge(u_of_edge, v_of_edge, **attr)


Add an edge between u and v.
The nodes u and v will be automatically added if they are not already in the graph.
Edge attributes can be specified with keywords or by directly accessing the edge’s attribute dictionary. See
examples below.
Parameters
• u, v (nodes) – Nodes can be, for example, strings or numbers. Nodes must be hashable (and
not None) Python objects.
• attr (keyword arguments, optional) – Edge data (or labels or objects) can be assigned using
keyword arguments.
See also:

add_edges_from() add a collection of edges

Notes

Adding an edge that already exists updates the edge data.


Many NetworkX algorithms designed for weighted graphs use an edge attribute (by default weight) to hold a
numerical value.

Examples

The following all add the edge e=(1, 2) to graph G:

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> e = (1, 2)
>>> G.add_edge(1, 2) # explicit two-node form
>>> G.add_edge(*e) # single edge as tuple of two nodes
>>> G.add_edges_from([(1, 2)]) # add edges from iterable container

Associate data to edges using keywords:

>>> G.add_edge(1, 2, weight=3)


>>> G.add_edge(1, 3, weight=7, capacity=15, length=342.7)

For non-string attribute keys, use subscript notation.

2.2. Basic graph types 15


NetworkX Reference, Release 2.5

>>> G.add_edge(1, 2)
>>> G[1][2].update({0: 5})
>>> [Link][1, 2].update({0: 5})

[Link].add_edges_from

Graph.add_edges_from(ebunch_to_add, **attr)
Add all the edges in ebunch_to_add.
Parameters
• ebunch_to_add (container of edges) – Each edge given in the container will be added to
the graph. The edges must be given as as 2-tuples (u, v) or 3-tuples (u, v, d) where d is a
dictionary containing edge data.
• attr (keyword arguments, optional) – Edge data (or labels or objects) can be assigned using
keyword arguments.
See also:

add_edge() add a single edge


add_weighted_edges_from() convenient way to add weighted edges

Notes

Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added.
Edge attributes specified in an ebunch take precedence over attributes specified via keyword arguments.

Examples

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
>>> e = zip(range(0, 3), range(1, 4))
>>> G.add_edges_from(e) # Add the path graph 0-1-2-3

Associate data to edges

>>> G.add_edges_from([(1, 2), (2, 3)], weight=3)


>>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")

[Link].add_weighted_edges_from

Graph.add_weighted_edges_from(ebunch_to_add, weight='weight', **attr)


Add weighted edges in ebunch_to_add with specified weight attr
Parameters
• ebunch_to_add (container of edges) – Each edge given in the list or container will be added
to the graph. The edges must be given as 3-tuples (u, v, w) where w is a number.
• weight (string, optional (default= ‘weight’)) – The attribute name for the edge weights to
be added.

16 Chapter 2. Graph types


NetworkX Reference, Release 2.5

• attr (keyword arguments, optional (default= no attributes)) – Edge attributes to add/update


for all edges.
See also:

add_edge() add a single edge


add_edges_from() add multiple edges

Notes

Adding the same edge twice for Graph/DiGraph simply updates the edge data. For MultiGraph/MultiDiGraph,
duplicate edges are stored.

Examples

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_weighted_edges_from([(0, 1, 3.0), (1, 2, 7.5)])

[Link].remove_edge

Graph.remove_edge(u, v)
Remove the edge between u and v.
Parameters u, v (nodes) – Remove the edge between nodes u and v.
Raises NetworkXError – If there is not an edge between u and v.
See also:

remove_edges_from() remove a collection of edges

Examples

>>> G = nx.path_graph(4) # or DiGraph, etc


>>> G.remove_edge(0, 1)
>>> e = (1, 2)
>>> G.remove_edge(*e) # unpacks e from an edge tuple
>>> e = (2, 3, {"weight": 7}) # an edge with attribute data
>>> G.remove_edge(*e[:2]) # select first part of edge tuple

[Link].remove_edges_from

Graph.remove_edges_from(ebunch)
Remove all edges specified in ebunch.
Parameters ebunch (list or container of edge tuples) – Each edge given in the list or container will
be removed from the graph. The edges can be:
• 2-tuples (u, v) edge between u and v.
• 3-tuples (u, v, k) where k is ignored.

2.2. Basic graph types 17


NetworkX Reference, Release 2.5

See also:

remove_edge() remove a single edge

Notes

Will fail silently if an edge in ebunch is not in the graph.

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> ebunch = [(1, 2), (2, 3)]
>>> G.remove_edges_from(ebunch)

[Link]

[Link](edges=None, nodes=None)
Update the graph using nodes/edges/graphs as input.
Like [Link], this method takes a graph as input, adding the graph’s nodes and edges to this graph. It can
also take two inputs: edges and nodes. Finally it can take either edges or nodes. To specify only nodes the
keyword nodes must be used.
The collections of edges and nodes are treated similarly to the add_edges_from/add_nodes_from methods.
When iterated, they should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
Parameters
• edges (Graph object, collection of edges, or None) – The first parameter can be a graph or
some edges. If it has attributes nodes and edges, then it is taken to be a Graph-like object
and those attributes are used as collections of nodes and edges to be added to the graph. If
the first parameter does not have those attributes, it is treated as a collection of edges and
added to the graph. If the first argument is None, no edges are added.
• nodes (collection of nodes, or None) – The second parameter is treated as a collection of
nodes to be added to the graph unless it is None. If edges is None and nodes is
None an exception is raised. If the first parameter is a Graph, then nodes is ignored.

Examples

>>> G = nx.path_graph(5)
>>> [Link](nx.complete_graph(range(4, 10)))
>>> from itertools import combinations
>>> edges = (
... (u, v, {"power": u * v})
... for u, v in combinations(range(10, 20), 2)
... if u * v < 225
... )
>>> nodes = [1000] # for singleton, use a container
>>> [Link](edges, nodes)

18 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Notes

It you want to update the graph using an adjacency structure it is straightforward to obtain the edges/nodes from
adjacency. The following examples provide common cases, your adjacency may be slightly different and require
tweaks of these examples.

>>> # dict-of-set/list/tuple
>>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}}
>>> e = [(u, v) for u, nbrs in [Link]() for v in nbrs]
>>> [Link](edges=e, nodes=adj)

>>> DG = [Link]()
>>> # dict-of-dict-of-attribute
>>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}}
>>> e = [
... (u, v, {"weight": d})
... for u, nbrs in [Link]()
... for v, d in [Link]()
... ]
>>> [Link](edges=e, nodes=adj)

>>> # dict-of-dict-of-dict
>>> adj = {1: {2: {"weight": 1.3}, 3: {"color": 0.7, "weight": 1.2}}}
>>> e = [
... (u, v, {"weight": d})
... for u, nbrs in [Link]()
... for v, d in [Link]()
... ]
>>> [Link](edges=e, nodes=adj)

>>> # predecessor adjacency (dict-of-set)


>>> pred = {1: {2, 3}, 2: {3}, 3: {3}}
>>> e = [(v, u) for u, nbrs in [Link]() for v in nbrs]

>>> # MultiGraph dict-of-dict-of-dict-of-attribute


>>> MDG = [Link]()
>>> adj = {
... 1: {2: {0: {"weight": 1.3}, 1: {"weight": 1.2}}},
... 3: {2: {0: {"weight": 0.7}}},
... }
>>> e = [
... (u, v, ekey, d)
... for u, nbrs in [Link]()
... for v, keydict in [Link]()
... for ekey, d in [Link]()
... ]
>>> [Link](edges=e)

See also:

add_edges_from() add multiple edges to a graph


add_nodes_from() add multiple nodes to a graph

2.2. Basic graph types 19


NetworkX Reference, Release 2.5

[Link]

[Link]()
Remove all nodes and edges from the graph.
This also removes the name, and all graph, node, and edge attributes.

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [Link]()
>>> list([Link])
[]
>>> list([Link])
[]

[Link].clear_edges

Graph.clear_edges()
Remove all edges from the graph without altering nodes.

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.clear_edges()
>>> list([Link])
[0, 1, 2, 3]
>>> list([Link])
[]

Reporting nodes edges and neighbors

[Link] A NodeView of the Graph as [Link] or [Link]().


Graph.__iter__() Iterate over the nodes.
Graph.has_node(n) Returns True if the graph contains the node n.
Graph.__contains__(n) Returns True if n is a node, False otherwise.
[Link] An EdgeView of the Graph as [Link] or [Link]().
Graph.has_edge(u, v) Returns True if the edge (u, v) is in the graph.
Graph.get_edge_data(u, v[, default]) Returns the attribute dictionary associated with edge (u,
v).
[Link](n) Returns an iterator over all neighbors of node n.
[Link] Graph adjacency object holding the neighbors of each
node.
Graph.__getitem__(n) Returns a dict of neighbors of node n.
[Link]() Returns an iterator over (node, adjacency dict) tuples for
all nodes.
Graph.nbunch_iter([nbunch]) Returns an iterator over nodes contained in nbunch that
are also in the graph.

20 Chapter 2. Graph types


NetworkX Reference, Release 2.5

[Link]

property [Link]
A NodeView of the Graph as [Link] or [Link]().
Can be used as [Link] for data lookup and for set-like operations. Can also be used as G.
nodes(data='color', default=None) to return a NodeDataView which reports specific node data
but no set operations. It presents a dict-like interface as well with [Link]() iterating over (node,
nodedata) 2-tuples and [Link][3]['foo'] providing the value of the foo attribute for node 3. In
addition, a view [Link]('foo') provides a dict-like interface to the foo attribute of each node.
[Link]('foo', default=1) provides a default for nodes that do not have attribute foo.
Parameters
• data (string or bool, optional (default=False)) – The node attribute returned in 2-tuple (n,
ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the
nodes n.
• default (value, optional (default=None)) – Value used for nodes that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns
Allows set-like operations over the nodes as well as node attribute dict lookup and calling to
get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A
NodeView iterates over n and includes set operations.
When called, if data is False, an iterator over nodes. Otherwise an iterator of 2-tuples (node,
attribute value) where the attribute is specified in data. If data is True then the attribute becomes
the entire data dictionary.
Return type NodeView

Notes

If your node data is not needed, it is simpler and equivalent to use the expression for n in G, or list(G).

Examples

There are two simple ways of getting a list of all nodes in the graph:

>>> G = nx.path_graph(3)
>>> list([Link])
[0, 1, 2]
>>> list(G)
[0, 1, 2]

To get the node data along with the nodes:

>>> G.add_node(1, time="5pm")


>>> [Link][0]["foo"] = "bar"
>>> list([Link](data=True))
[(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
>>> list([Link]())
[(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]

2.2. Basic graph types 21


NetworkX Reference, Release 2.5

>>> list([Link](data="foo"))
[(0, 'bar'), (1, None), (2, None)]
>>> list([Link]("foo"))
[(0, 'bar'), (1, None), (2, None)]

>>> list([Link](data="time"))
[(0, None), (1, '5pm'), (2, None)]
>>> list([Link]("time"))
[(0, None), (1, '5pm'), (2, None)]

>>> list([Link](data="time", default="Not Available"))


[(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
>>> list([Link]("time", default="Not Available"))
[(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]

If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create
a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never
None:

>>> G = [Link]()
>>> G.add_node(0)
>>> G.add_node(1, weight=2)
>>> G.add_node(2, weight=3)
>>> dict([Link](data="weight", default=1))
{0: 1, 1: 2, 2: 3}

[Link].__iter__

Graph.__iter__()
Iterate over the nodes. Use: ‘for n in G’.
Returns niter – An iterator over all nodes in the graph.
Return type iterator

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [n for n in G]
[0, 1, 2, 3]
>>> list(G)
[0, 1, 2, 3]

22 Chapter 2. Graph types


NetworkX Reference, Release 2.5

[Link].has_node

Graph.has_node(n)
Returns True if the graph contains the node n.
Identical to n in G
Parameters n (node)

Examples

>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.has_node(0)
True

It is more readable and simpler to use

>>> 0 in G
True

[Link].__contains__

Graph.__contains__(n)
Returns True if n is a node, False otherwise. Use: ‘n in G’.

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> 1 in G
True

[Link]

property [Link]
An EdgeView of the Graph as [Link] or [Link]().
edges(self, nbunch=None, data=False, default=None)
The EdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called,
it also provides an EdgeDataView object which allows control of access to edge attributes (but does not pro-
vide set-like operations). Hence, [Link][u, v]['color'] provides the value of the color attribute for
edge (u, v) while for (u, v, c) in [Link]('color', default='red'): iterates
through all the edges yielding the color attribute with default 'red' if no color attribute exists.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).

2.2. Basic graph types 23


NetworkX Reference, Release 2.5

• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns edges – A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges,
but can also be used for attribute lookup as edges[u, v]['foo'].
Return type EdgeView

Notes

Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.

Examples

>>> G = nx.path_graph(3) # or MultiGraph, etc


>>> G.add_edge(2, 3, weight=5)
>>> [e for e in [Link]]
[(0, 1), (1, 2), (2, 3)]
>>> [Link]() # default data is {} (empty dict)
EdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
>>> [Link]("weight", default=1)
EdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
>>> [Link]([0, 3]) # only edges incident to these nodes
EdgeDataView([(0, 1), (3, 2)])
>>> [Link](0) # only edges incident to a single node (use [Link][0]?)
EdgeDataView([(0, 1)])

[Link].has_edge

Graph.has_edge(u, v)
Returns True if the edge (u, v) is in the graph.
This is the same as v in G[u] without KeyError exceptions.
Parameters u, v (nodes) – Nodes can be, for example, strings or numbers. Nodes must be hashable
(and not None) Python objects.
Returns edge_ind – True if edge is in the graph, False otherwise.
Return type bool

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.has_edge(0, 1) # using two nodes
True
>>> e = (0, 1)
>>> G.has_edge(*e) # e is a 2-tuple (u, v)
True
>>> e = (0, 1, {"weight": 7})
>>> G.has_edge(*e[:2]) # e is a 3-tuple (u, v, data_dictionary)
True

The following syntax are equivalent:

24 Chapter 2. Graph types


NetworkX Reference, Release 2.5

>>> G.has_edge(0, 1)
True
>>> 1 in G[0] # though this gives KeyError if 0 not in G
True

[Link].get_edge_data

Graph.get_edge_data(u, v, default=None)
Returns the attribute dictionary associated with edge (u, v).
This is identical to G[u][v] except the default is returned instead of an exception if the edge doesn’t exist.
Parameters
• u, v (nodes)
• default (any Python object (default=None)) – Value to return if the edge (u, v) is not found.
Returns edge_dict – The edge attribute dictionary.
Return type dictionary

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G[0][1]
{}

Warning: Assigning to G[u][v] is not permitted. But it is safe to assign attributes G[u][v]['foo']

>>> G[0][1]["weight"] = 7
>>> G[0][1]["weight"]
7
>>> G[1][0]["weight"]
7

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.get_edge_data(0, 1) # default edge data is {}
{}
>>> e = (0, 1)
>>> G.get_edge_data(*e) # tuple form
{}
>>> G.get_edge_data("a", "b", default=0) # edge not in graph, return 0
0

2.2. Basic graph types 25


NetworkX Reference, Release 2.5

[Link]

[Link](n)
Returns an iterator over all neighbors of node n.
This is identical to iter(G[n])
Parameters n (node) – A node in the graph
Returns neighbors – An iterator over all neighbors of node n
Return type iterator
Raises NetworkXError – If the node n is not in the graph.

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [n for n in [Link](0)]
[1]

Notes

Alternate ways to access the neighbors are [Link][n] or G[n]:

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_edge("a", "b", weight=7)
>>> G["a"]
AtlasView({'b': {'weight': 7}})
>>> G = nx.path_graph(4)
>>> [n for n in G[0]]
[1]

[Link]

property [Link]
Graph adjacency object holding the neighbors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed
by neighbor to the edge-data-dict. So [Link][3][2]['color'] = 'blue' sets the color of the edge (3,
2) to "blue".
Iterating over [Link] behaves like a dict. Useful idioms include for nbr, datadict in [Link][n].
items():.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in
G[node].data('foo', default=1): works.
For directed graphs, [Link] holds outgoing (successor) info.

26 Chapter 2. Graph types


NetworkX Reference, Release 2.5

[Link].__getitem__

Graph.__getitem__(n)
Returns a dict of neighbors of node n. Use: ‘G[n]’.
Parameters n (node) – A node in the graph.
Returns adj_dict – The adjacency dictionary for nodes connected to n.
Return type dictionary

Notes

G[n] is the same as [Link][n] and similar to [Link](n) (which is an iterator over [Link][n])

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G[0]
AtlasView({1: {}})

[Link]

[Link]()
Returns an iterator over (node, adjacency dict) tuples for all nodes.
For directed graphs, only outgoing neighbors/adjacencies are included.
Returns adj_iter – An iterator over (node, adjacency dictionary) for all nodes in the graph.
Return type iterator

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [(n, nbrdict) for n, nbrdict in [Link]()]
[(0, {1: {}}), (1, {0: {}, 2: {}}), (2, {1: {}, 3: {}}), (3, {2: {}})]

[Link].nbunch_iter

Graph.nbunch_iter(nbunch=None)
Returns an iterator over nodes contained in nbunch that are also in the graph.
The nodes in nbunch are checked for membership in the graph and if not are silently ignored.
Parameters nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
Returns niter – An iterator over nodes in nbunch that are also in the graph. If nbunch is None,
iterate over all nodes in the graph.
Return type iterator

2.2. Basic graph types 27


NetworkX Reference, Release 2.5

Raises NetworkXError – If nbunch is not a node or or sequence of nodes. If a node in nbunch is


not hashable.
See also:
Graph.__iter__()

Notes

When nbunch is an iterator, the returned iterator yields values directly from nbunch, becoming exhausted when
nbunch is exhausted.
To test whether nbunch is a single node, one can use “if nbunch in self:”, even after processing with this routine.
If nbunch is not a node or a (possibly empty) sequence/iterator or None, a NetworkXError is raised. Also, if
any object in nbunch is not hashable, a NetworkXError is raised.

Counting nodes edges and neighbors

[Link]() Returns the number of nodes in the graph.


Graph.number_of_nodes() Returns the number of nodes in the graph.
Graph.__len__() Returns the number of nodes in the graph.
[Link] A DegreeView for the Graph as [Link] or [Link]().
[Link]([weight]) Returns the number of edges or total of all edge weights.
Graph.number_of_edges([u, v]) Returns the number of edges between two nodes.

[Link]

[Link]()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
number_of_nodes(), __len__()

28 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Examples

>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [Link]()
3

[Link].number_of_nodes

Graph.number_of_nodes()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
order(), __len__()

Examples

>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.number_of_nodes()
3

[Link].__len__

Graph.__len__()
Returns the number of nodes in the graph. Use: ‘len(G)’.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
number_of_nodes(), order()

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> len(G)
4

2.2. Basic graph types 29


NetworkX Reference, Release 2.5

[Link]

property [Link]
A DegreeView for the Graph as [Link] or [Link]().
The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge
weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The name of an edge attribute that holds
the numerical value used as a weight. If None, then each edge has weight 1. The degree is
the sum of the edge weights adjacent to the node.
Returns
• If a single node is requested
• deg (int) – Degree of the node
• OR if multiple nodes are requested
• nd_view (A DegreeView object capable of iterating (node, degree) pairs)

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [Link][0] # node 0 has degree 1
1
>>> list([Link]([0, 1, 2]))
[(0, 1), (1, 2), (2, 2)]

[Link]

[Link](weight=None)
Returns the number of edges or total of all edge weights.
Parameters weight (string or None, optional (default=None)) – The edge attribute that holds the
numerical value used as a weight. If None, then each edge has weight 1.
Returns
size – The number of edges or (if weight keyword is provided) the total weight sum.
If weight is None, returns an int. Otherwise a float (or more general numeric if the weights are
more general).
Return type numeric
See also:
number_of_edges()

30 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [Link]()
3

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_edge("a", "b", weight=2)
>>> G.add_edge("b", "c", weight=4)
>>> [Link]()
2
>>> [Link](weight="weight")
6.0

[Link].number_of_edges

Graph.number_of_edges(u=None, v=None)
Returns the number of edges between two nodes.
Parameters u, v (nodes, optional (default=all edges)) – If u and v are specified, return the number
of edges between u and v. Otherwise return the total number of all edges.
Returns nedges – The number of edges in the graph. If nodes u and v are specified return the
number of edges between those nodes. If the graph is directed, this only returns the number of
edges from u to v.
Return type int
See also:
size()

Examples

For undirected graphs, this method counts the total number of edges in the graph:

>>> G = nx.path_graph(4)
>>> G.number_of_edges()
3

If you specify two nodes, this counts the total number of edges joining the two nodes:

>>> G.number_of_edges(0, 1)
1

For directed graphs, this method can count the total number of directed edges from u to v:

>>> G = [Link]()
>>> G.add_edge(0, 1)
>>> G.add_edge(1, 0)
>>> G.number_of_edges(0, 1)
1

2.2. Basic graph types 31


NetworkX Reference, Release 2.5

Making copies and subgraphs

[Link]([as_view]) Returns a copy of the graph.


Graph.to_undirected([as_view]) Returns an undirected copy of the graph.
Graph.to_directed([as_view]) Returns a directed representation of the graph.
[Link](nodes) Returns a SubGraph view of the subgraph induced on
nodes.
Graph.edge_subgraph(edges) Returns the subgraph induced by the specified edges.

[Link]

[Link](as_view=False)
Returns a copy of the graph.
The copy method by default returns an independent shallow copy of the graph and attributes. That is, if an
attribute is a container, that container is shared by the original an the copy. Use Python’s [Link] for
new containers.
If as_view is True then a view is returned instead of a copy.

Notes

All copies reproduce the graph structure, but data attributes may be handled in different ways. There are four
types of copies of a graph that people might want.
Deepcopy – A “deepcopy” copies the graph structure as well as all data attributes and any objects they might
contain. The entire graph object is new so that changes in the copy do not affect the original object. (see Python’s
[Link])
Data Reference (Shallow) – For a shallow copy the graph structure is copied but the edge, node and graph at-
tribute dicts are references to those in the original graph. This saves time and memory but could cause confusion
if you change an attribute in one graph and it changes the attribute in the other. NetworkX does not provide this
level of shallow copy.
Independent Shallow – This copy creates new independent attribute dicts and then does a shallow copy of the
attributes. That is, any attributes that are containers are shared between the new graph and the original. This is
exactly what [Link]() provides. You can obtain this style copy using:

>>> G = nx.path_graph(5)
>>> H = [Link]()
>>> H = [Link](as_view=False)
>>> H = [Link](G)
>>> H = G.__class__(G)

Fresh Data – For fresh data, the graph structure is copied while new empty data attribute dicts are created. The
resulting graph is independent of the original and it has no edge, node or graph attributes. Fresh copies are not
enabled. Instead use:

>>> H = G.__class__()
>>> H.add_nodes_from(G)
>>> H.add_edges_from([Link])

View – Inspired by dict-views, graph-views act like read-only versions of the original graph, providing a copy
of the original structure without requiring any memory for copying the information.

32 Chapter 2. Graph types


NetworkX Reference, Release 2.5

See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Parameters as_view (bool, optional (default=False)) – If True, the returned graph-view provides a
read-only view of the original graph without actually copying any data.
Returns G – A copy of the graph.
Return type Graph
See also:

to_directed() return a directed copy of the graph.

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> H = [Link]()

[Link].to_undirected

Graph.to_undirected(as_view=False)
Returns an undirected copy of the graph.
Parameters as_view (bool (optional, default=False)) – If True return a view of the original undi-
rected graph.
Returns G – A deepcopy of the graph.
Return type Graph/MultiGraph
See also:
Graph(), copy(), add_edge(), add_edges_from()

Notes

This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar G = [Link](D) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Warning: If you have subclassed DiGraph to use dict-like objects in the data structure, those changes do not
transfer to the Graph created by this method.

2.2. Basic graph types 33


NetworkX Reference, Release 2.5

Examples

>>> G = nx.path_graph(2) # or MultiGraph, etc


>>> H = G.to_directed()
>>> list([Link])
[(0, 1), (1, 0)]
>>> G2 = H.to_undirected()
>>> list([Link])
[(0, 1)]

[Link].to_directed

Graph.to_directed(as_view=False)
Returns a directed representation of the graph.
Returns G – A directed graph with the same name, same nodes, and with each edge (u, v, data)
replaced by two directed edges (u, v, data) and (v, u, data).
Return type DiGraph

Notes

This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar D=DiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Warning: If you have subclassed Graph to use dict-like objects in the data structure, those changes do not
transfer to the DiGraph created by this method.

Examples

>>> G = [Link]() # or MultiGraph, etc


>>> G.add_edge(0, 1)
>>> H = G.to_directed()
>>> list([Link])
[(0, 1), (1, 0)]

If already directed, return a (deep) copy

>>> G = [Link]() # or MultiDiGraph, etc


>>> G.add_edge(0, 1)
>>> H = G.to_directed()
>>> list([Link])
[(0, 1)]

34 Chapter 2. Graph types


NetworkX Reference, Release 2.5

[Link]

[Link](nodes)
Returns a SubGraph view of the subgraph induced on nodes.
The induced subgraph of the graph contains the nodes in nodes and the edges between those nodes.
Parameters nodes (list, iterable) – A container of nodes which will be iterated through once.
Returns G – A subgraph view of the graph. The graph structure cannot be changed but node/edge
attributes can and are shared with the original graph.
Return type SubGraph View

Notes

The graph, edge and node attributes are shared with the original graph. Changes to the graph structure is ruled
out by the view, but changes to attributes are reflected in the original graph.
To create a subgraph with its own copy of the edge/node attributes use: [Link](nodes).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(nodes)])
Subgraph views are sometimes NOT what you want. In most cases where you want to do more than simply look
at the induced edges, it makes more sense to just create the subgraph as its own graph with code like:

# Create a subgraph SG based on a (possibly multigraph) G


SG = G.__class__()
SG.add_nodes_from((n, [Link][n]) for n in largest_wcc)
if SG.is_multigraph():
SG.add_edges_from((n, nbr, key, d)
for n, nbrs in [Link]() if n in largest_wcc
for nbr, keydict in [Link]() if nbr in largest_wcc
for key, d in [Link]())
else:
SG.add_edges_from((n, nbr, d)
for n, nbrs in [Link]() if n in largest_wcc
for nbr, d in [Link]() if nbr in largest_wcc)
[Link]([Link])

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> H = [Link]([0, 1, 2])
>>> list([Link])
[(0, 1), (1, 2)]

2.2. Basic graph types 35


NetworkX Reference, Release 2.5

[Link].edge_subgraph

Graph.edge_subgraph(edges)
Returns the subgraph induced by the specified edges.
The induced subgraph contains each edge in edges and each node incident to any one of those edges.
Parameters edges (iterable) – An iterable of edges in this graph.
Returns G – An edge-induced subgraph of this 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()

Examples

>>> G = nx.path_graph(5)
>>> H = G.edge_subgraph([(0, 1), (3, 4)])
>>> list([Link])
[0, 1, 3, 4]
>>> list([Link])
[(0, 1), (3, 4)]

2.2.2 DiGraph—Directed graphs with self loops

Overview

class DiGraph(incoming_graph_data=None, **attr)


Base class for directed graphs.
A DiGraph stores nodes and edges with optional data, or attributes.
DiGraphs hold directed edges. Self loops are allowed but multiple (parallel) edges are not.
Nodes can be arbitrary (hashable) Python objects with optional key/value attributes. By convention None is not
used as a node.
Edges are represented as links between nodes with optional key/value attributes.
Parameters
• incoming_graph_data (input graph (optional, default: None)) – Data to initialize graph. If
None (default) an empty graph is created. The data can be any format that is supported by
the to_networkx_graph() function, currently including edge list, dict of dicts, dict of lists,
NetworkX graph, NumPy matrix or 2d ndarray, SciPy sparse matrix, or PyGraphviz graph.
• attr (keyword arguments, optional (default= no attributes)) – Attributes to add to graph as
key=value pairs.

36 Chapter 2. Graph types


NetworkX Reference, Release 2.5

See also:
Graph, MultiGraph, MultiDiGraph, OrderedDiGraph

Examples

Create an empty graph structure (a “null graph”) with no nodes and no edges.

>>> G = [Link]()

G can be grown in several ways.


Nodes:
Add one node at a time:

>>> G.add_node(1)

Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph).

>>> G.add_nodes_from([2, 3])


>>> G.add_nodes_from(range(100, 110))
>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)

In addition to strings and integers any hashable Python object (except None) can represent a node, e.g. a
customized node object, or even another Graph.

>>> G.add_node(H)

Edges:
G can also be grown by adding edges.
Add one edge,

>>> G.add_edge(1, 2)

a list of edges,

>>> G.add_edges_from([(1, 2), (1, 3)])

or a collection of edges,

>>> G.add_edges_from([Link])

If some edges connect nodes not yet in the graph, the nodes are added automatically. There are no errors when
adding nodes or edges that already exist.
Attributes:
Each graph, node, and edge can hold key/value attribute pairs in an associated attribute dictionary (the keys
must be hashable). By default these are empty, but can be added or changed using add_edge, add_node or direct
manipulation of the attribute dictionaries named graph, node and edge respectively.

>>> G = [Link](day="Friday")
>>> [Link]
{'day': 'Friday'}

2.2. Basic graph types 37


NetworkX Reference, Release 2.5

Add node attributes using add_node(), add_nodes_from() or [Link]

>>> G.add_node(1, time="5pm")


>>> G.add_nodes_from([3], time="2pm")
>>> [Link][1]
{'time': '5pm'}
>>> [Link][1]["room"] = 714
>>> del [Link][1]["room"] # remove attribute
>>> list([Link](data=True))
[(1, {'time': '5pm'}), (3, {'time': '2pm'})]

Add edge attributes using add_edge(), add_edges_from(), subscript notation, or [Link].

>>> G.add_edge(1, 2, weight=4.7)


>>> G.add_edges_from([(3, 4), (4, 5)], color="red")
>>> G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
>>> G[1][2]["weight"] = 4.7
>>> [Link][1, 2]["weight"] = 4

Warning: we protect the graph data structure by making [Link][1, 2] a read-only dict-like structure.
However, you can assign to attributes in e.g. [Link][1, 2]. Thus, use 2 sets of brackets to add/change data
attributes: [Link][1, 2]['weight'] = 4 (For multigraphs: [Link][u, v, key][name] =
value).
Shortcuts:
Many common graph features allow python syntax to speed reporting.

>>> 1 in G # check if node in graph


True
>>> [n for n in G if n < 3] # iterate through nodes
[1, 2]
>>> len(G) # number of nodes in graph
5

Often the best way to traverse all edges of a graph is via the neighbors. The neighbors are reported as an
adjacency-dict [Link] or [Link]()

>>> for n, nbrsdict in [Link]():


... for nbr, eattr in [Link]():
... if "weight" in eattr:
... # Do something useful with the edges
... pass

But the edges reporting object is often more convenient:

>>> for u, v, weight in [Link](data="weight"):


... if weight is not None:
... # Do something useful with the edges
... pass

Reporting:
Simple graph information is obtained using object-attributes and methods. Reporting usually provides
views instead of containers to reduce memory usage. The views update as the graph is updated simi-
larly to dict-views. The objects nodes, `edges and adj provide access to data attributes via lookup
(e.g. nodes[n], `edges[u, v], adj[u][v]) and iteration (e.g. [Link](), nodes.
data('color'), [Link]('color', default='blue') and similarly for edges) Views exist
for nodes, edges, neighbors()/adj and degree.

38 Chapter 2. Graph types


NetworkX Reference, Release 2.5

For details on these and other miscellaneous methods, see below.


Subclasses (Advanced):
The Graph class uses a dict-of-dict-of-dict data structure. The outer dict (node_dict) holds adjacency information
keyed by node. The next dict (adjlist_dict) represents the adjacency information and holds edge data keyed by
neighbor. The inner dict (edge_attr_dict) represents the edge data and holds edge attribute values keyed by
attribute names.
Each of these three dicts can be replaced in a subclass by a user defined dict-like object. In general, the
dict-like features should be maintained but extra features can be added. To replace one of the dicts create
a new graph class by changing the class(!) variable holding the factory for that dict-like structure. The vari-
able names are node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory, adjlist_outer_dict_factory,
edge_attr_dict_factory and graph_attr_dict_factory.
node_dict_factory [function, (default: dict)] Factory function to be used to create the dict containing node
attributes, keyed by node id. It should require no arguments and return a dict-like object
node_attr_dict_factory: function, (default: dict) Factory function to be used to create the node attribute dict
which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like
object
adjlist_outer_dict_factory [function, (default: dict)] Factory function to be used to create the outer-most dict
in the data structure that holds adjacency info keyed by node. It should require no arguments and return a
dict-like object.
adjlist_inner_dict_factory [function, optional (default: dict)] Factory function to be used to create the adja-
cency list dict which holds edge data keyed by neighbor. It should require no arguments and return a
dict-like object
edge_attr_dict_factory [function, optional (default: dict)] Factory function to be used to create the edge at-
tribute dict which holds attribute values keyed by attribute name. It should require no arguments and return
a dict-like object.
graph_attr_dict_factory [function, (default: dict)] Factory function to be used to create the graph attribute
dict which holds attribute values keyed by attribute name. It should require no arguments and return a
dict-like object.
Typically, if your extension doesn’t impact the data structure all methods will inherited without issue except:
to_directed/to_undirected. By default these methods create a DiGraph/Graph class and you probably
want them to create your extension of a DiGraph/Graph. To facilitate this we define two class variables that you
can set in your subclass.
to_directed_class [callable, (default: DiGraph or MultiDiGraph)] Class to create a new graph structure in the
to_directed method. If None, a NetworkX class (DiGraph or MultiDiGraph) is used.
to_undirected_class [callable, (default: Graph or MultiGraph)] Class to create a new graph structure in the
to_undirected method. If None, a NetworkX class (Graph or MultiGraph) is used.

Examples

Create a low memory graph class that effectively disallows edge attributes by using a single attribute dict for all
edges. This reduces the memory used, but you lose edge attributes.

>>> class ThinGraph([Link]):


... all_edge_dict = {"weight": 1}
...
... def single_edge_dict(self):
... return self.all_edge_dict
(continues on next page)

2.2. Basic graph types 39


NetworkX Reference, Release 2.5

(continued from previous page)


...
... edge_attr_dict_factory = single_edge_dict
>>> G = ThinGraph()
>>> G.add_edge(2, 1)
>>> G[2][1]
{'weight': 1}
>>> G.add_edge(2, 2)
>>> G[2][1] is G[2][2]
True

Please see ordered for more examples of creating graph subclasses by overwriting the base class dict with
a dictionary-like object.

Methods

Adding and removing nodes and edges

DiGraph.__init__([incoming_graph_data]) Initialize a graph with edges, name, or graph attributes.


DiGraph.add_node(node_for_adding, **attr) Add a single node node_for_adding and update
node attributes.
DiGraph.add_nodes_from(nodes_for_adding, Add multiple nodes.
**attr)
DiGraph.remove_node(n) Remove node n.
DiGraph.remove_nodes_from(nodes) Remove multiple nodes.
DiGraph.add_edge(u_of_edge, v_of_edge, **attr) Add an edge between u and v.
DiGraph.add_edges_from(ebunch_to_add, Add all the edges in ebunch_to_add.
**attr)
DiGraph.add_weighted_edges_from(ebunch_to_add) Add weighted edges in ebunch_to_add with speci-
fied weight attr
DiGraph.remove_edge(u, v) Remove the edge between u and v.
DiGraph.remove_edges_from(ebunch) Remove all edges specified in ebunch.
[Link]([edges, nodes]) Update the graph using nodes/edges/graphs as input.
[Link]() Remove all nodes and edges from the graph.
DiGraph.clear_edges() Remove all edges from the graph without altering
nodes.

[Link].__init__

DiGraph.__init__(incoming_graph_data=None, **attr)
Initialize a graph with edges, name, or graph attributes.
Parameters
• incoming_graph_data (input graph (optional, default: None)) – Data to initialize graph. If
None (default) an empty graph is created. The data can be an edge list, or any NetworkX
graph object. If the corresponding optional Python packages are installed the data can also
be a NumPy matrix or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz graph.
• attr (keyword arguments, optional (default= no attributes)) – Attributes to add to graph as
key=value pairs.
See also:

40 Chapter 2. Graph types


NetworkX Reference, Release 2.5

convert()

Examples

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G = [Link](name="my graph")
>>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
>>> G = [Link](e)

Arbitrary graph attribute pairs (key=value) may be assigned

>>> G = [Link](e, day="Friday")


>>> [Link]
{'day': 'Friday'}

[Link].add_node

DiGraph.add_node(node_for_adding, **attr)
Add a single node node_for_adding and update node attributes.
Parameters
• node_for_adding (node) – A node can be any hashable Python object except None.
• attr (keyword arguments, optional) – Set or change node attributes using key=value.
See also:
add_nodes_from()

Examples

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_node(1)
>>> G.add_node("Hello")
>>> K3 = [Link]([(0, 1), (1, 2), (2, 0)])
>>> G.add_node(K3)
>>> G.number_of_nodes()
3

Use keywords set/change node attributes:

>>> G.add_node(1, size=10)


>>> G.add_node(3, weight=0.4, UTM=("13S", 382871, 3972649))

2.2. Basic graph types 41


NetworkX Reference, Release 2.5

Notes

A hashable object is one that can be used as a key in a Python dictionary. This includes strings, numbers, tuples
of strings and numbers, etc.
On many platforms hashable items also include mutables such as NetworkX Graphs, though one should be
careful that the hash doesn’t change on mutables.

[Link].add_nodes_from

DiGraph.add_nodes_from(nodes_for_adding, **attr)
Add multiple nodes.
Parameters
• nodes_for_adding (iterable container) – A container of nodes (list, dict, set, etc.). OR A
container of (node, attribute dict) tuples. Node attributes are updated using the attribute dict.
• attr (keyword arguments, optional (default= no attributes)) – Update attributes for all nodes
in nodes. Node attributes specified in nodes as a tuple take precedence over attributes spec-
ified via keyword arguments.
See also:
add_node()

Examples

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_nodes_from("Hello")
>>> K3 = [Link]([(0, 1), (1, 2), (2, 0)])
>>> G.add_nodes_from(K3)
>>> sorted([Link](), key=str)
[0, 1, 2, 'H', 'e', 'l', 'o']

Use keywords to update specific node attributes for every node.

>>> G.add_nodes_from([1, 2], size=10)


>>> G.add_nodes_from([3, 4], weight=0.4)

Use (node, attrdict) tuples to update attributes for specific nodes.

>>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})])


>>> [Link][1]["size"]
11
>>> H = [Link]()
>>> H.add_nodes_from([Link](data=True))
>>> [Link][1]["size"]
11

42 Chapter 2. Graph types


NetworkX Reference, Release 2.5

[Link].remove_node

DiGraph.remove_node(n)
Remove node n.
Removes the node n and all adjacent edges. Attempting to remove a non-existent node will raise an exception.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
remove_nodes_from()

Examples

>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> list([Link])
[(0, 1), (1, 2)]
>>> G.remove_node(1)
>>> list([Link])
[]

[Link].remove_nodes_from

DiGraph.remove_nodes_from(nodes)
Remove multiple nodes.
Parameters nodes (iterable container) – A container of nodes (list, dict, set, etc.). If a node in the
container is not in the graph it is silently ignored.
See also:
remove_node()

Examples

>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> e = list([Link])
>>> e
[0, 1, 2]
>>> G.remove_nodes_from(e)
>>> list([Link])
[]

2.2. Basic graph types 43


NetworkX Reference, Release 2.5

[Link].add_edge

DiGraph.add_edge(u_of_edge, v_of_edge, **attr)


Add an edge between u and v.
The nodes u and v will be automatically added if they are not already in the graph.
Edge attributes can be specified with keywords or by directly accessing the edge’s attribute dictionary. See
examples below.
Parameters
• u, v (nodes) – Nodes can be, for example, strings or numbers. Nodes must be hashable (and
not None) Python objects.
• attr (keyword arguments, optional) – Edge data (or labels or objects) can be assigned using
keyword arguments.
See also:

add_edges_from() add a collection of edges

Notes

Adding an edge that already exists updates the edge data.


Many NetworkX algorithms designed for weighted graphs use an edge attribute (by default weight) to hold a
numerical value.

Examples

The following all add the edge e=(1, 2) to graph G:

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> e = (1, 2)
>>> G.add_edge(1, 2) # explicit two-node form
>>> G.add_edge(*e) # single edge as tuple of two nodes
>>> G.add_edges_from([(1, 2)]) # add edges from iterable container

Associate data to edges using keywords:

>>> G.add_edge(1, 2, weight=3)


>>> G.add_edge(1, 3, weight=7, capacity=15, length=342.7)

For non-string attribute keys, use subscript notation.

>>> G.add_edge(1, 2)
>>> G[1][2].update({0: 5})
>>> [Link][1, 2].update({0: 5})

44 Chapter 2. Graph types


NetworkX Reference, Release 2.5

[Link].add_edges_from

DiGraph.add_edges_from(ebunch_to_add, **attr)
Add all the edges in ebunch_to_add.
Parameters
• ebunch_to_add (container of edges) – Each edge given in the container will be added to the
graph. The edges must be given as 2-tuples (u, v) or 3-tuples (u, v, d) where d is a dictionary
containing edge data.
• attr (keyword arguments, optional) – Edge data (or labels or objects) can be assigned using
keyword arguments.
See also:

add_edge() add a single edge


add_weighted_edges_from() convenient way to add weighted edges

Notes

Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added.
Edge attributes specified in an ebunch take precedence over attributes specified via keyword arguments.

Examples

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
>>> e = zip(range(0, 3), range(1, 4))
>>> G.add_edges_from(e) # Add the path graph 0-1-2-3

Associate data to edges

>>> G.add_edges_from([(1, 2), (2, 3)], weight=3)


>>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")

[Link].add_weighted_edges_from

DiGraph.add_weighted_edges_from(ebunch_to_add, weight='weight', **attr)


Add weighted edges in ebunch_to_add with specified weight attr
Parameters
• ebunch_to_add (container of edges) – Each edge given in the list or container will be added
to the graph. The edges must be given as 3-tuples (u, v, w) where w is a number.
• weight (string, optional (default= ‘weight’)) – The attribute name for the edge weights to
be added.
• attr (keyword arguments, optional (default= no attributes)) – Edge attributes to add/update
for all edges.
See also:

add_edge() add a single edge

2.2. Basic graph types 45


NetworkX Reference, Release 2.5

add_edges_from() add multiple edges

Notes

Adding the same edge twice for Graph/DiGraph simply updates the edge data. For MultiGraph/MultiDiGraph,
duplicate edges are stored.

Examples

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_weighted_edges_from([(0, 1, 3.0), (1, 2, 7.5)])

[Link].remove_edge

DiGraph.remove_edge(u, v)
Remove the edge between u and v.
Parameters u, v (nodes) – Remove the edge between nodes u and v.
Raises NetworkXError – If there is not an edge between u and v.
See also:

remove_edges_from() remove a collection of edges

Examples

>>> G = [Link]() # or DiGraph, etc


>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.remove_edge(0, 1)
>>> e = (1, 2)
>>> G.remove_edge(*e) # unpacks e from an edge tuple
>>> e = (2, 3, {"weight": 7}) # an edge with attribute data
>>> G.remove_edge(*e[:2]) # select first part of edge tuple

[Link].remove_edges_from

DiGraph.remove_edges_from(ebunch)
Remove all edges specified in ebunch.
Parameters ebunch (list or container of edge tuples) – Each edge given in the list or container will
be removed from the graph. The edges can be:
• 2-tuples (u, v) edge between u and v.
• 3-tuples (u, v, k) where k is ignored.
See also:

remove_edge() remove a single edge

46 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Notes

Will fail silently if an edge in ebunch is not in the graph.

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> ebunch = [(1, 2), (2, 3)]
>>> G.remove_edges_from(ebunch)

[Link]

[Link](edges=None, nodes=None)
Update the graph using nodes/edges/graphs as input.
Like [Link], this method takes a graph as input, adding the graph’s nodes and edges to this graph. It can
also take two inputs: edges and nodes. Finally it can take either edges or nodes. To specify only nodes the
keyword nodes must be used.
The collections of edges and nodes are treated similarly to the add_edges_from/add_nodes_from methods.
When iterated, they should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
Parameters
• edges (Graph object, collection of edges, or None) – The first parameter can be a graph or
some edges. If it has attributes nodes and edges, then it is taken to be a Graph-like object
and those attributes are used as collections of nodes and edges to be added to the graph. If
the first parameter does not have those attributes, it is treated as a collection of edges and
added to the graph. If the first argument is None, no edges are added.
• nodes (collection of nodes, or None) – The second parameter is treated as a collection of
nodes to be added to the graph unless it is None. If edges is None and nodes is
None an exception is raised. If the first parameter is a Graph, then nodes is ignored.

Examples

>>> G = nx.path_graph(5)
>>> [Link](nx.complete_graph(range(4, 10)))
>>> from itertools import combinations
>>> edges = (
... (u, v, {"power": u * v})
... for u, v in combinations(range(10, 20), 2)
... if u * v < 225
... )
>>> nodes = [1000] # for singleton, use a container
>>> [Link](edges, nodes)

2.2. Basic graph types 47


NetworkX Reference, Release 2.5

Notes

It you want to update the graph using an adjacency structure it is straightforward to obtain the edges/nodes from
adjacency. The following examples provide common cases, your adjacency may be slightly different and require
tweaks of these examples.

>>> # dict-of-set/list/tuple
>>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}}
>>> e = [(u, v) for u, nbrs in [Link]() for v in nbrs]
>>> [Link](edges=e, nodes=adj)

>>> DG = [Link]()
>>> # dict-of-dict-of-attribute
>>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}}
>>> e = [
... (u, v, {"weight": d})
... for u, nbrs in [Link]()
... for v, d in [Link]()
... ]
>>> [Link](edges=e, nodes=adj)

>>> # dict-of-dict-of-dict
>>> adj = {1: {2: {"weight": 1.3}, 3: {"color": 0.7, "weight": 1.2}}}
>>> e = [
... (u, v, {"weight": d})
... for u, nbrs in [Link]()
... for v, d in [Link]()
... ]
>>> [Link](edges=e, nodes=adj)

>>> # predecessor adjacency (dict-of-set)


>>> pred = {1: {2, 3}, 2: {3}, 3: {3}}
>>> e = [(v, u) for u, nbrs in [Link]() for v in nbrs]

>>> # MultiGraph dict-of-dict-of-dict-of-attribute


>>> MDG = [Link]()
>>> adj = {
... 1: {2: {0: {"weight": 1.3}, 1: {"weight": 1.2}}},
... 3: {2: {0: {"weight": 0.7}}},
... }
>>> e = [
... (u, v, ekey, d)
... for u, nbrs in [Link]()
... for v, keydict in [Link]()
... for ekey, d in [Link]()
... ]
>>> [Link](edges=e)

See also:

add_edges_from() add multiple edges to a graph


add_nodes_from() add multiple nodes to a graph

48 Chapter 2. Graph types


NetworkX Reference, Release 2.5

[Link]

[Link]()
Remove all nodes and edges from the graph.
This also removes the name, and all graph, node, and edge attributes.

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [Link]()
>>> list([Link])
[]
>>> list([Link])
[]

[Link].clear_edges

DiGraph.clear_edges()
Remove all edges from the graph without altering nodes.

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.clear_edges()
>>> list([Link])
[0, 1, 2, 3]
>>> list([Link])
[]

Reporting nodes edges and neighbors

[Link] A NodeView of the Graph as [Link] or [Link]().


DiGraph.__iter__() Iterate over the nodes.
DiGraph.has_node(n) Returns True if the graph contains the node n.
DiGraph.__contains__(n) Returns True if n is a node, False otherwise.
[Link] An OutEdgeView of the DiGraph as [Link] or
[Link]().
DiGraph.out_edges An OutEdgeView of the DiGraph as [Link] or
[Link]().
DiGraph.in_edges An InEdgeView of the Graph as G.in_edges or
G.in_edges().
DiGraph.has_edge(u, v) Returns True if the edge (u, v) is in the graph.
DiGraph.get_edge_data(u, v[, default]) Returns the attribute dictionary associated with edge (u,
v).
[Link](n) Returns an iterator over successor nodes of n.
[Link] Graph adjacency object holding the neighbors of each
node.
continues on next page

2.2. Basic graph types 49


NetworkX Reference, Release 2.5

Table 6 – continued from previous page


DiGraph.__getitem__(n) Returns a dict of neighbors of node n.
[Link](n) Returns an iterator over successor nodes of n.
[Link] Graph adjacency object holding the successors of each
node.
[Link](n) Returns an iterator over predecessor nodes of n.
[Link] Graph adjacency object holding the predecessors of
each node.
[Link]() Returns an iterator over (node, adjacency dict) tuples for
all nodes.
DiGraph.nbunch_iter([nbunch]) Returns an iterator over nodes contained in nbunch that
are also in the graph.

[Link]

property [Link]
A NodeView of the Graph as [Link] or [Link]().
Can be used as [Link] for data lookup and for set-like operations. Can also be used as G.
nodes(data='color', default=None) to return a NodeDataView which reports specific node data
but no set operations. It presents a dict-like interface as well with [Link]() iterating over (node,
nodedata) 2-tuples and [Link][3]['foo'] providing the value of the foo attribute for node 3. In
addition, a view [Link]('foo') provides a dict-like interface to the foo attribute of each node.
[Link]('foo', default=1) provides a default for nodes that do not have attribute foo.
Parameters
• data (string or bool, optional (default=False)) – The node attribute returned in 2-tuple (n,
ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the
nodes n.
• default (value, optional (default=None)) – Value used for nodes that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns
Allows set-like operations over the nodes as well as node attribute dict lookup and calling to
get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A
NodeView iterates over n and includes set operations.
When called, if data is False, an iterator over nodes. Otherwise an iterator of 2-tuples (node,
attribute value) where the attribute is specified in data. If data is True then the attribute becomes
the entire data dictionary.
Return type NodeView

50 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Notes

If your node data is not needed, it is simpler and equivalent to use the expression for n in G, or list(G).

Examples

There are two simple ways of getting a list of all nodes in the graph:

>>> G = nx.path_graph(3)
>>> list([Link])
[0, 1, 2]
>>> list(G)
[0, 1, 2]

To get the node data along with the nodes:

>>> G.add_node(1, time="5pm")


>>> [Link][0]["foo"] = "bar"
>>> list([Link](data=True))
[(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
>>> list([Link]())
[(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]

>>> list([Link](data="foo"))
[(0, 'bar'), (1, None), (2, None)]
>>> list([Link]("foo"))
[(0, 'bar'), (1, None), (2, None)]

>>> list([Link](data="time"))
[(0, None), (1, '5pm'), (2, None)]
>>> list([Link]("time"))
[(0, None), (1, '5pm'), (2, None)]

>>> list([Link](data="time", default="Not Available"))


[(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
>>> list([Link]("time", default="Not Available"))
[(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]

If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create
a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never
None:

>>> G = [Link]()
>>> G.add_node(0)
>>> G.add_node(1, weight=2)
>>> G.add_node(2, weight=3)
>>> dict([Link](data="weight", default=1))
{0: 1, 1: 2, 2: 3}

2.2. Basic graph types 51


NetworkX Reference, Release 2.5

[Link].__iter__

DiGraph.__iter__()
Iterate over the nodes. Use: ‘for n in G’.
Returns niter – An iterator over all nodes in the graph.
Return type iterator

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [n for n in G]
[0, 1, 2, 3]
>>> list(G)
[0, 1, 2, 3]

[Link].has_node

DiGraph.has_node(n)
Returns True if the graph contains the node n.
Identical to n in G
Parameters n (node)

Examples

>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.has_node(0)
True

It is more readable and simpler to use

>>> 0 in G
True

[Link].__contains__

DiGraph.__contains__(n)
Returns True if n is a node, False otherwise. Use: ‘n in G’.

52 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> 1 in G
True

[Link]

property [Link]
An OutEdgeView of the DiGraph as [Link] or [Link]().
edges(self, nbunch=None, data=False, default=None)
The OutEdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called,
it also provides an EdgeDataView object which allows control of access to edge attributes (but does not pro-
vide set-like operations). Hence, [Link][u, v]['color'] provides the value of the color attribute for
edge (u, v) while for (u, v, c) in [Link]('color', default='red'): iterates
through all the edges yielding the color attribute with default 'red' if no color attribute exists.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns edges – A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges,
but can also be used for attribute lookup as edges[u, v]['foo'].
Return type OutEdgeView
See also:
in_edges, out_edges

Notes

Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.

Examples

>>> G = [Link]() # or MultiDiGraph, etc


>>> nx.add_path(G, [0, 1, 2])
>>> G.add_edge(2, 3, weight=5)
>>> [e for e in [Link]]
[(0, 1), (1, 2), (2, 3)]
>>> [Link]() # default data is {} (empty dict)
OutEdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
>>> [Link]("weight", default=1)
OutEdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
>>> [Link]([0, 2]) # only edges incident to these nodes
(continues on next page)

2.2. Basic graph types 53


NetworkX Reference, Release 2.5

(continued from previous page)


OutEdgeDataView([(0, 1), (2, 3)])
>>> [Link](0) # only edges incident to a single node (use [Link][0]?)
OutEdgeDataView([(0, 1)])

[Link].out_edges

property DiGraph.out_edges
An OutEdgeView of the DiGraph as [Link] or [Link]().
edges(self, nbunch=None, data=False, default=None)
The OutEdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called,
it also provides an EdgeDataView object which allows control of access to edge attributes (but does not pro-
vide set-like operations). Hence, [Link][u, v]['color'] provides the value of the color attribute for
edge (u, v) while for (u, v, c) in [Link]('color', default='red'): iterates
through all the edges yielding the color attribute with default 'red' if no color attribute exists.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns edges – A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges,
but can also be used for attribute lookup as edges[u, v]['foo'].
Return type OutEdgeView
See also:
in_edges, out_edges

Notes

Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.

Examples

>>> G = [Link]() # or MultiDiGraph, etc


>>> nx.add_path(G, [0, 1, 2])
>>> G.add_edge(2, 3, weight=5)
>>> [e for e in [Link]]
[(0, 1), (1, 2), (2, 3)]
>>> [Link]() # default data is {} (empty dict)
OutEdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
>>> [Link]("weight", default=1)
OutEdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
>>> [Link]([0, 2]) # only edges incident to these nodes
OutEdgeDataView([(0, 1), (2, 3)])
(continues on next page)

54 Chapter 2. Graph types


NetworkX Reference, Release 2.5

(continued from previous page)


>>> [Link](0) # only edges incident to a single node (use [Link][0]?)
OutEdgeDataView([(0, 1)])

[Link].in_edges

property DiGraph.in_edges
An InEdgeView of the Graph as G.in_edges or G.in_edges().
in_edges(self, nbunch=None, data=False, default=None):
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns in_edges – A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of
edges, but can also be used for attribute lookup as edges[u, v]['foo'].
Return type InEdgeView
See also:
edges

[Link].has_edge

DiGraph.has_edge(u, v)
Returns True if the edge (u, v) is in the graph.
This is the same as v in G[u] without KeyError exceptions.
Parameters u, v (nodes) – Nodes can be, for example, strings or numbers. Nodes must be hashable
(and not None) Python objects.
Returns edge_ind – True if edge is in the graph, False otherwise.
Return type bool

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.has_edge(0, 1) # using two nodes
True
>>> e = (0, 1)
>>> G.has_edge(*e) # e is a 2-tuple (u, v)
True
>>> e = (0, 1, {"weight": 7})
>>> G.has_edge(*e[:2]) # e is a 3-tuple (u, v, data_dictionary)
True

2.2. Basic graph types 55


NetworkX Reference, Release 2.5

The following syntax are equivalent:

>>> G.has_edge(0, 1)
True
>>> 1 in G[0] # though this gives KeyError if 0 not in G
True

[Link].get_edge_data

DiGraph.get_edge_data(u, v, default=None)
Returns the attribute dictionary associated with edge (u, v).
This is identical to G[u][v] except the default is returned instead of an exception if the edge doesn’t exist.
Parameters
• u, v (nodes)
• default (any Python object (default=None)) – Value to return if the edge (u, v) is not found.
Returns edge_dict – The edge attribute dictionary.
Return type dictionary

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G[0][1]
{}

Warning: Assigning to G[u][v] is not permitted. But it is safe to assign attributes G[u][v]['foo']

>>> G[0][1]["weight"] = 7
>>> G[0][1]["weight"]
7
>>> G[1][0]["weight"]
7

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.get_edge_data(0, 1) # default edge data is {}
{}
>>> e = (0, 1)
>>> G.get_edge_data(*e) # tuple form
{}
>>> G.get_edge_data("a", "b", default=0) # edge not in graph, return 0
0

56 Chapter 2. Graph types


NetworkX Reference, Release 2.5

[Link]

[Link](n)
Returns an iterator over successor nodes of n.
A successor of n is a node m such that there exists a directed edge from n to m.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
predecessors()

Notes

neighbors() and successors() are the same.

[Link]

property [Link]
Graph adjacency object holding the neighbors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed
by neighbor to the edge-data-dict. So [Link][3][2]['color'] = 'blue' sets the color of the edge (3,
2) to "blue".
Iterating over [Link] behaves like a dict. Useful idioms include for nbr, datadict in [Link][n].
items():.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in
G[node].data('foo', default=1): works.
For directed graphs, [Link] holds outgoing (successor) info.

[Link].__getitem__

DiGraph.__getitem__(n)
Returns a dict of neighbors of node n. Use: ‘G[n]’.
Parameters n (node) – A node in the graph.
Returns adj_dict – The adjacency dictionary for nodes connected to n.
Return type dictionary

2.2. Basic graph types 57


NetworkX Reference, Release 2.5

Notes

G[n] is the same as [Link][n] and similar to [Link](n) (which is an iterator over [Link][n])

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G[0]
AtlasView({1: {}})

[Link]

[Link](n)
Returns an iterator over successor nodes of n.
A successor of n is a node m such that there exists a directed edge from n to m.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
predecessors()

Notes

neighbors() and successors() are the same.

[Link]

property [Link]
Graph adjacency object holding the successors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is
keyed by neighbor to the edge-data-dict. So [Link][3][2]['color'] = 'blue' sets the color of the
edge (3, 2) to "blue".
Iterating over [Link] behaves like a dict. Useful idioms include for nbr, datadict in [Link][n].
items():. A data-view not provided by dicts also exists: for nbr, foovalue in [Link][node].
data('foo'): and a default can be set via a default argument to the data method.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in
G[node].data('foo', default=1): works.
For directed graphs, [Link] is identical to [Link].

58 Chapter 2. Graph types


NetworkX Reference, Release 2.5

[Link]

[Link](n)
Returns an iterator over predecessor nodes of n.
A predecessor of n is a node m such that there exists a directed edge from m to n.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
successors()

[Link]

property [Link]
Graph adjacency object holding the predecessors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is
keyed by neighbor to the edge-data-dict. So [Link][2][3]['color'] = 'blue' sets the color of the
edge (3, 2) to "blue".
Iterating over [Link] behaves like a dict. Useful idioms include for nbr, datadict in [Link][n].
items():. A data-view not provided by dicts also exists: for nbr, foovalue in [Link][node].
data('foo'): A default can be set via a default argument to the data method.

[Link]

[Link]()
Returns an iterator over (node, adjacency dict) tuples for all nodes.
For directed graphs, only outgoing neighbors/adjacencies are included.
Returns adj_iter – An iterator over (node, adjacency dictionary) for all nodes in the graph.
Return type iterator

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [(n, nbrdict) for n, nbrdict in [Link]()]
[(0, {1: {}}), (1, {0: {}, 2: {}}), (2, {1: {}, 3: {}}), (3, {2: {}})]

[Link].nbunch_iter

DiGraph.nbunch_iter(nbunch=None)
Returns an iterator over nodes contained in nbunch that are also in the graph.
The nodes in nbunch are checked for membership in the graph and if not are silently ignored.
Parameters nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.

2.2. Basic graph types 59


NetworkX Reference, Release 2.5

Returns niter – An iterator over nodes in nbunch that are also in the graph. If nbunch is None,
iterate over all nodes in the graph.
Return type iterator
Raises NetworkXError – If nbunch is not a node or or sequence of nodes. If a node in nbunch is
not hashable.
See also:
Graph.__iter__()

Notes

When nbunch is an iterator, the returned iterator yields values directly from nbunch, becoming exhausted when
nbunch is exhausted.
To test whether nbunch is a single node, one can use “if nbunch in self:”, even after processing with this routine.
If nbunch is not a node or a (possibly empty) sequence/iterator or None, a NetworkXError is raised. Also, if
any object in nbunch is not hashable, a NetworkXError is raised.

Counting nodes edges and neighbors

[Link]() Returns the number of nodes in the graph.


DiGraph.number_of_nodes() Returns the number of nodes in the graph.
DiGraph.__len__() Returns the number of nodes in the graph.
[Link] A DegreeView for the Graph as [Link] or [Link]().
DiGraph.in_degree An InDegreeView for (node, in_degree) or in_degree
for single node.
DiGraph.out_degree An OutDegreeView for (node, out_degree)
[Link]([weight]) Returns the number of edges or total of all edge weights.
DiGraph.number_of_edges([u, v]) Returns the number of edges between two nodes.

[Link]

[Link]()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
number_of_nodes(), __len__()

60 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Examples

>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [Link]()
3

[Link].number_of_nodes

DiGraph.number_of_nodes()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
order(), __len__()

Examples

>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.number_of_nodes()
3

[Link].__len__

DiGraph.__len__()
Returns the number of nodes in the graph. Use: ‘len(G)’.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
number_of_nodes(), order()

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> len(G)
4

2.2. Basic graph types 61


NetworkX Reference, Release 2.5

[Link]

property [Link]
A DegreeView for the Graph as [Link] or [Link]().
The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge
weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The name of an edge attribute that holds
the numerical value used as a weight. If None, then each edge has weight 1. The degree is
the sum of the edge weights adjacent to the node.
Returns
• If a single node is requested
• deg (int) – Degree of the node
• OR if multiple nodes are requested
• nd_iter (iterator) – The iterator returns two-tuples of (node, degree).
See also:
in_degree, out_degree

Examples

>>> G = [Link]() # or MultiDiGraph


>>> nx.add_path(G, [0, 1, 2, 3])
>>> [Link](0) # node 0 with degree 1
1
>>> list([Link]([0, 1, 2]))
[(0, 1), (1, 2), (2, 2)]

[Link].in_degree

property DiGraph.in_degree
An InDegreeView for (node, in_degree) or in_degree for single node.
The node in_degree is the number of edges pointing to the node. The weighted node degree is the sum of the
edge weights for edges incident to that node.
This object provides an iteration over (node, in_degree) as well as lookup for the degree for a single node.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The name of an edge attribute that holds
the numerical value used as a weight. If None, then each edge has weight 1. The degree is
the sum of the edge weights adjacent to the node.

62 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Returns
• If a single node is requested
• deg (int) – In-degree of the node
• OR if multiple nodes are requested
• nd_iter (iterator) – The iterator returns two-tuples of (node, in-degree).
See also:
degree, out_degree

Examples

>>> G = [Link]()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.in_degree(0) # node 0 with degree 0
0
>>> list(G.in_degree([0, 1, 2]))
[(0, 0), (1, 1), (2, 1)]

[Link].out_degree

property DiGraph.out_degree
An OutDegreeView for (node, out_degree)
The node out_degree is the number of edges pointing out of the node. The weighted node degree is the sum of
the edge weights for edges incident to that node.
This object provides an iterator over (node, out_degree) as well as lookup for the degree for a single node.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The name of an edge attribute that holds
the numerical value used as a weight. If None, then each edge has weight 1. The degree is
the sum of the edge weights adjacent to the node.
Returns
• If a single node is requested
• deg (int) – Out-degree of the node
• OR if multiple nodes are requested
• nd_iter (iterator) – The iterator returns two-tuples of (node, out-degree).
See also:
degree, in_degree

2.2. Basic graph types 63


NetworkX Reference, Release 2.5

Examples

>>> G = [Link]()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.out_degree(0) # node 0 with degree 1
1
>>> list(G.out_degree([0, 1, 2]))
[(0, 1), (1, 1), (2, 1)]

[Link]

[Link](weight=None)
Returns the number of edges or total of all edge weights.
Parameters weight (string or None, optional (default=None)) – The edge attribute that holds the
numerical value used as a weight. If None, then each edge has weight 1.
Returns
size – The number of edges or (if weight keyword is provided) the total weight sum.
If weight is None, returns an int. Otherwise a float (or more general numeric if the weights are
more general).
Return type numeric
See also:
number_of_edges()

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [Link]()
3

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_edge("a", "b", weight=2)
>>> G.add_edge("b", "c", weight=4)
>>> [Link]()
2
>>> [Link](weight="weight")
6.0

[Link].number_of_edges

DiGraph.number_of_edges(u=None, v=None)
Returns the number of edges between two nodes.
Parameters u, v (nodes, optional (default=all edges)) – If u and v are specified, return the number
of edges between u and v. Otherwise return the total number of all edges.
Returns nedges – The number of edges in the graph. If nodes u and v are specified return the
number of edges between those nodes. If the graph is directed, this only returns the number of
edges from u to v.

64 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Return type int


See also:
size()

Examples

For undirected graphs, this method counts the total number of edges in the graph:

>>> G = nx.path_graph(4)
>>> G.number_of_edges()
3

If you specify two nodes, this counts the total number of edges joining the two nodes:

>>> G.number_of_edges(0, 1)
1

For directed graphs, this method can count the total number of directed edges from u to v:

>>> G = [Link]()
>>> G.add_edge(0, 1)
>>> G.add_edge(1, 0)
>>> G.number_of_edges(0, 1)
1

Making copies and subgraphs

[Link]([as_view]) Returns a copy of the graph.


DiGraph.to_undirected([reciprocal, as_view]) Returns an undirected representation of the digraph.
DiGraph.to_directed([as_view]) Returns a directed representation of the graph.
[Link](nodes) Returns a SubGraph view of the subgraph induced on
nodes.
DiGraph.edge_subgraph(edges) Returns the subgraph induced by the specified edges.
[Link]([copy]) Returns the reverse of the graph.

[Link]

[Link](as_view=False)
Returns a copy of the graph.
The copy method by default returns an independent shallow copy of the graph and attributes. That is, if an
attribute is a container, that container is shared by the original an the copy. Use Python’s [Link] for
new containers.
If as_view is True then a view is returned instead of a copy.

2.2. Basic graph types 65


NetworkX Reference, Release 2.5

Notes

All copies reproduce the graph structure, but data attributes may be handled in different ways. There are four
types of copies of a graph that people might want.
Deepcopy – A “deepcopy” copies the graph structure as well as all data attributes and any objects they might
contain. The entire graph object is new so that changes in the copy do not affect the original object. (see Python’s
[Link])
Data Reference (Shallow) – For a shallow copy the graph structure is copied but the edge, node and graph at-
tribute dicts are references to those in the original graph. This saves time and memory but could cause confusion
if you change an attribute in one graph and it changes the attribute in the other. NetworkX does not provide this
level of shallow copy.
Independent Shallow – This copy creates new independent attribute dicts and then does a shallow copy of the
attributes. That is, any attributes that are containers are shared between the new graph and the original. This is
exactly what [Link]() provides. You can obtain this style copy using:

>>> G = nx.path_graph(5)
>>> H = [Link]()
>>> H = [Link](as_view=False)
>>> H = [Link](G)
>>> H = G.__class__(G)

Fresh Data – For fresh data, the graph structure is copied while new empty data attribute dicts are created. The
resulting graph is independent of the original and it has no edge, node or graph attributes. Fresh copies are not
enabled. Instead use:

>>> H = G.__class__()
>>> H.add_nodes_from(G)
>>> H.add_edges_from([Link])

View – Inspired by dict-views, graph-views act like read-only versions of the original graph, providing a copy
of the original structure without requiring any memory for copying the information.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Parameters as_view (bool, optional (default=False)) – If True, the returned graph-view provides a
read-only view of the original graph without actually copying any data.
Returns G – A copy of the graph.
Return type Graph
See also:

to_directed() return a directed copy of the graph.

66 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> H = [Link]()

[Link].to_undirected

DiGraph.to_undirected(reciprocal=False, as_view=False)
Returns an undirected representation of the digraph.
Parameters
• reciprocal (bool (optional)) – If True only keep edges that appear in both directions in the
original digraph.
• as_view (bool (optional, default=False)) – If True return an undirected view of the original
directed graph.
Returns G – An undirected graph with the same name and nodes and with edge (u, v, data) if either
(u, v, data) or (v, u, data) is in the digraph. If both edges exist in digraph and their edge data is
different, only one edge is created with an arbitrary choice of which edge data to use. You must
check and correct for this manually if desired.
Return type Graph
See also:
Graph(), copy(), add_edge(), add_edges_from()

Notes

If edges in both directions (u, v) and (v, u) exist in the graph, attributes for the new undirected edge will be a
combination of the attributes of the directed edges. The edge data is updated in the (arbitrary) order that the
edges are encountered. For more customized control of the edge attributes use add_edge().
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar G=DiGraph(D) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Warning: If you have subclassed DiGraph to use dict-like objects in the data structure, those changes do not
transfer to the Graph created by this method.

Examples

>>> G = nx.path_graph(2) # or MultiGraph, etc


>>> H = G.to_directed()
>>> list([Link])
[(0, 1), (1, 0)]
>>> G2 = H.to_undirected()
>>> list([Link])
[(0, 1)]

2.2. Basic graph types 67


NetworkX Reference, Release 2.5

[Link].to_directed

DiGraph.to_directed(as_view=False)
Returns a directed representation of the graph.
Returns G – A directed graph with the same name, same nodes, and with each edge (u, v, data)
replaced by two directed edges (u, v, data) and (v, u, data).
Return type DiGraph

Notes

This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar D=DiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Warning: If you have subclassed Graph to use dict-like objects in the data structure, those changes do not
transfer to the DiGraph created by this method.

Examples

>>> G = [Link]() # or MultiGraph, etc


>>> G.add_edge(0, 1)
>>> H = G.to_directed()
>>> list([Link])
[(0, 1), (1, 0)]

If already directed, return a (deep) copy

>>> G = [Link]() # or MultiDiGraph, etc


>>> G.add_edge(0, 1)
>>> H = G.to_directed()
>>> list([Link])
[(0, 1)]

[Link]

[Link](nodes)
Returns a SubGraph view of the subgraph induced on nodes.
The induced subgraph of the graph contains the nodes in nodes and the edges between those nodes.
Parameters nodes (list, iterable) – A container of nodes which will be iterated through once.
Returns G – A subgraph view of the graph. The graph structure cannot be changed but node/edge
attributes can and are shared with the original graph.
Return type SubGraph View

68 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Notes

The graph, edge and node attributes are shared with the original graph. Changes to the graph structure is ruled
out by the view, but changes to attributes are reflected in the original graph.
To create a subgraph with its own copy of the edge/node attributes use: [Link](nodes).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(nodes)])
Subgraph views are sometimes NOT what you want. In most cases where you want to do more than simply look
at the induced edges, it makes more sense to just create the subgraph as its own graph with code like:

# Create a subgraph SG based on a (possibly multigraph) G


SG = G.__class__()
SG.add_nodes_from((n, [Link][n]) for n in largest_wcc)
if SG.is_multigraph():
SG.add_edges_from((n, nbr, key, d)
for n, nbrs in [Link]() if n in largest_wcc
for nbr, keydict in [Link]() if nbr in largest_wcc
for key, d in [Link]())
else:
SG.add_edges_from((n, nbr, d)
for n, nbrs in [Link]() if n in largest_wcc
for nbr, d in [Link]() if nbr in largest_wcc)
[Link]([Link])

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> H = [Link]([0, 1, 2])
>>> list([Link])
[(0, 1), (1, 2)]

[Link].edge_subgraph

DiGraph.edge_subgraph(edges)
Returns the subgraph induced by the specified edges.
The induced subgraph contains each edge in edges and each node incident to any one of those edges.
Parameters edges (iterable) – An iterable of edges in this graph.
Returns G – An edge-induced subgraph of this graph with the same edge attributes.
Return type Graph

2.2. Basic graph types 69


NetworkX Reference, Release 2.5

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()

Examples

>>> G = nx.path_graph(5)
>>> H = G.edge_subgraph([(0, 1), (3, 4)])
>>> list([Link])
[0, 1, 3, 4]
>>> list([Link])
[(0, 1), (3, 4)]

[Link]

[Link](copy=True)
Returns the reverse of the graph.
The reverse is a graph with the same nodes and edges but with the directions of the edges reversed.
Parameters copy (bool optional (default=True)) – If True, return a new DiGraph holding the re-
versed edges. If False, the reverse graph is created using a view of the original graph.

2.2.3 MultiGraph—Undirected graphs with self loops and parallel edges

Overview

class MultiGraph(incoming_graph_data=None, **attr)


An undirected graph class that can store multiedges.
Multiedges are multiple edges between two nodes. Each edge can hold optional data or attributes.
A MultiGraph holds undirected edges. Self loops are allowed.
Nodes can be arbitrary (hashable) Python objects with optional key/value attributes. By convention None is not
used as a node.
Edges are represented as links between nodes with optional key/value attributes.
Parameters
• incoming_graph_data (input graph (optional, default: None)) – Data to initialize graph. If
None (default) an empty graph is created. The data can be any format that is supported by
the to_networkx_graph() function, currently including edge list, dict of dicts, dict of lists,
NetworkX graph, NumPy matrix or 2d ndarray, SciPy sparse matrix, or PyGraphviz graph.
• attr (keyword arguments, optional (default= no attributes)) – Attributes to add to graph as
key=value pairs.
See also:
Graph, DiGraph, MultiDiGraph, OrderedMultiGraph

70 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Examples

Create an empty graph structure (a “null graph”) with no nodes and no edges.

>>> G = [Link]()

G can be grown in several ways.


Nodes:
Add one node at a time:

>>> G.add_node(1)

Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph).

>>> G.add_nodes_from([2, 3])


>>> G.add_nodes_from(range(100, 110))
>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)

In addition to strings and integers any hashable Python object (except None) can represent a node, e.g. a
customized node object, or even another Graph.

>>> G.add_node(H)

Edges:
G can also be grown by adding edges.
Add one edge,

>>> key = G.add_edge(1, 2)

a list of edges,

>>> keys = G.add_edges_from([(1, 2), (1, 3)])

or a collection of edges,

>>> keys = G.add_edges_from([Link])

If some edges connect nodes not yet in the graph, the nodes are added automatically. If an edge already exists,
an additional edge is created and stored using a key to identify the edge. By default the key is the lowest unused
integer.

>>> keys = G.add_edges_from([(4, 5, {"route": 28}), (4, 5, {"route": 37})])


>>> G[4]
AdjacencyView({3: {0: {}}, 5: {0: {}, 1: {'route': 28}, 2: {'route': 37}}})

Attributes:
Each graph, node, and edge can hold key/value attribute pairs in an associated attribute dictionary (the keys
must be hashable). By default these are empty, but can be added or changed using add_edge, add_node or direct
manipulation of the attribute dictionaries named graph, node and edge respectively.

>>> G = [Link](day="Friday")
>>> [Link]
{'day': 'Friday'}

2.2. Basic graph types 71


NetworkX Reference, Release 2.5

Add node attributes using add_node(), add_nodes_from() or [Link]

>>> G.add_node(1, time="5pm")


>>> G.add_nodes_from([3], time="2pm")
>>> [Link][1]
{'time': '5pm'}
>>> [Link][1]["room"] = 714
>>> del [Link][1]["room"] # remove attribute
>>> list([Link](data=True))
[(1, {'time': '5pm'}), (3, {'time': '2pm'})]

Add edge attributes using add_edge(), add_edges_from(), subscript notation, or [Link].

>>> key = G.add_edge(1, 2, weight=4.7)


>>> keys = G.add_edges_from([(3, 4), (4, 5)], color="red")
>>> keys = G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
>>> G[1][2][0]["weight"] = 4.7
>>> [Link][1, 2, 0]["weight"] = 4

Warning: we protect the graph data structure by making [Link][1, 2] a read-only dict-like structure.
However, you can assign to attributes in e.g. [Link][1, 2]. Thus, use 2 sets of brackets to add/change data
attributes: [Link][1, 2]['weight'] = 4 (For multigraphs: [Link][u, v, key][name] =
value).
Shortcuts:
Many common graph features allow python syntax to speed reporting.

>>> 1 in G # check if node in graph


True
>>> [n for n in G if n < 3] # iterate through nodes
[1, 2]
>>> len(G) # number of nodes in graph
5
>>> G[1] # adjacency dict-like view keyed by neighbor to edge attributes
AdjacencyView({2: {0: {'weight': 4}, 1: {'color': 'blue'}}})

Often the best way to traverse all edges of a graph is via the neighbors. The neighbors are reported as an
adjacency-dict [Link] or [Link]().

>>> for n, nbrsdict in [Link]():


... for nbr, keydict in [Link]():
... for key, eattr in [Link]():
... if "weight" in eattr:
... # Do something useful with the edges
... pass

But the edges() method is often more convenient:

>>> for u, v, keys, weight in [Link](data="weight", keys=True):


... if weight is not None:
... # Do something useful with the edges
... pass

Reporting:
Simple graph information is obtained using methods and object-attributes. Reporting usually provides
views instead of containers to reduce memory usage. The views update as the graph is updated simi-
larly to dict-views. The objects nodes, `edges and adj provide access to data attributes via lookup

72 Chapter 2. Graph types


NetworkX Reference, Release 2.5

(e.g. nodes[n], `edges[u, v], adj[u][v]) and iteration (e.g. [Link](), nodes.
data('color'), [Link]('color', default='blue') and similarly for edges) Views exist
for nodes, edges, neighbors()/adj and degree.
For details on these and other miscellaneous methods, see below.
Subclasses (Advanced):
The MultiGraph class uses a dict-of-dict-of-dict-of-dict data structure. The outer dict (node_dict) holds adja-
cency information keyed by node. The next dict (adjlist_dict) represents the adjacency information and holds
edge_key dicts keyed by neighbor. The edge_key dict holds each edge_attr dict keyed by edge key. The inner
dict (edge_attr_dict) represents the edge data and holds edge attribute values keyed by attribute names.
Each of these four dicts in the dict-of-dict-of-dict-of-dict structure can be replaced by a user defined dict-like
object. In general, the dict-like features should be maintained but extra features can be added. To replace
one of the dicts create a new graph class by changing the class(!) variable holding the factory for that dict-
like structure. The variable names are node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory and graph_attr_dict_factory.
node_dict_factory [function, (default: dict)] Factory function to be used to create the dict containing node
attributes, keyed by node id. It should require no arguments and return a dict-like object
node_attr_dict_factory: function, (default: dict) Factory function to be used to create the node attribute dict
which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like
object
adjlist_outer_dict_factory [function, (default: dict)] Factory function to be used to create the outer-most dict
in the data structure that holds adjacency info keyed by node. It should require no arguments and return a
dict-like object.
adjlist_inner_dict_factory [function, (default: dict)] Factory function to be used to create the adjacency list
dict which holds multiedge key dicts keyed by neighbor. It should require no arguments and return a
dict-like object.
edge_key_dict_factory [function, (default: dict)] Factory function to be used to create the edge key dict which
holds edge data keyed by edge key. It should require no arguments and return a dict-like object.
edge_attr_dict_factory [function, (default: dict)] Factory function to be used to create the edge attribute dict
which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like
object.
graph_attr_dict_factory [function, (default: dict)] Factory function to be used to create the graph attribute
dict which holds attribute values keyed by attribute name. It should require no arguments and return a
dict-like object.
Typically, if your extension doesn’t impact the data structure all methods will inherited without issue except:
to_directed/to_undirected. By default these methods create a DiGraph/Graph class and you probably
want them to create your extension of a DiGraph/Graph. To facilitate this we define two class variables that you
can set in your subclass.
to_directed_class [callable, (default: DiGraph or MultiDiGraph)] Class to create a new graph structure in the
to_directed method. If None, a NetworkX class (DiGraph or MultiDiGraph) is used.
to_undirected_class [callable, (default: Graph or MultiGraph)] Class to create a new graph structure in the
to_undirected method. If None, a NetworkX class (Graph or MultiGraph) is used.

2.2. Basic graph types 73


NetworkX Reference, Release 2.5

Examples

Please see ordered for examples of creating graph subclasses by overwriting the base class dict with a
dictionary-like object.

Methods

Adding and removing nodes and edges

MultiGraph.__init__([incoming_graph_data]) Initialize a graph with edges, name, or graph attributes.


MultiGraph.add_node(node_for_adding, **attr)Add a single node node_for_adding and update
node attributes.
MultiGraph.add_nodes_from(nodes_for_adding, Add multiple nodes.
...)
MultiGraph.remove_node(n) Remove node n.
MultiGraph.remove_nodes_from(nodes) Remove multiple nodes.
MultiGraph.add_edge(u_for_edge, v_for_edge) Add an edge between u and v.
MultiGraph.add_edges_from(ebunch_to_add, Add all the edges in ebunch_to_add.
**attr)
Add weighted edges in ebunch_to_add with speci-
MultiGraph.add_weighted_edges_from(ebunch_to_add)
fied weight attr
MultiGraph.new_edge_key(u, v) Returns an unused key for edges between nodes u and
v.
MultiGraph.remove_edge(u, v[, key]) Remove an edge between u and v.
MultiGraph.remove_edges_from(ebunch) Remove all edges specified in ebunch.
[Link]([edges, nodes]) Update the graph using nodes/edges/graphs as input.
[Link]() Remove all nodes and edges from the graph.
MultiGraph.clear_edges() Remove all edges from the graph without altering
nodes.

[Link].__init__

MultiGraph.__init__(incoming_graph_data=None, **attr)
Initialize a graph with edges, name, or graph attributes.
Parameters
• incoming_graph_data (input graph) – Data to initialize graph. If incom-
ing_graph_data=None (default) an empty graph is created. The data can be an edge list,
or any NetworkX graph object. If the corresponding optional Python packages are installed
the data can also be a NumPy matrix or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz
graph.
• attr (keyword arguments, optional (default= no attributes)) – Attributes to add to graph as
key=value pairs.
See also:
convert()

74 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Examples

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G = [Link](name="my graph")
>>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
>>> G = [Link](e)

Arbitrary graph attribute pairs (key=value) may be assigned

>>> G = [Link](e, day="Friday")


>>> [Link]
{'day': 'Friday'}

[Link].add_node

MultiGraph.add_node(node_for_adding, **attr)
Add a single node node_for_adding and update node attributes.
Parameters
• node_for_adding (node) – A node can be any hashable Python object except None.
• attr (keyword arguments, optional) – Set or change node attributes using key=value.
See also:
add_nodes_from()

Examples

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_node(1)
>>> G.add_node("Hello")
>>> K3 = [Link]([(0, 1), (1, 2), (2, 0)])
>>> G.add_node(K3)
>>> G.number_of_nodes()
3

Use keywords set/change node attributes:

>>> G.add_node(1, size=10)


>>> G.add_node(3, weight=0.4, UTM=("13S", 382871, 3972649))

Notes

A hashable object is one that can be used as a key in a Python dictionary. This includes strings, numbers, tuples
of strings and numbers, etc.
On many platforms hashable items also include mutables such as NetworkX Graphs, though one should be
careful that the hash doesn’t change on mutables.

2.2. Basic graph types 75


NetworkX Reference, Release 2.5

[Link].add_nodes_from

MultiGraph.add_nodes_from(nodes_for_adding, **attr)
Add multiple nodes.
Parameters
• nodes_for_adding (iterable container) – A container of nodes (list, dict, set, etc.). OR A
container of (node, attribute dict) tuples. Node attributes are updated using the attribute dict.
• attr (keyword arguments, optional (default= no attributes)) – Update attributes for all nodes
in nodes. Node attributes specified in nodes as a tuple take precedence over attributes spec-
ified via keyword arguments.
See also:
add_node()

Examples

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_nodes_from("Hello")
>>> K3 = [Link]([(0, 1), (1, 2), (2, 0)])
>>> G.add_nodes_from(K3)
>>> sorted([Link](), key=str)
[0, 1, 2, 'H', 'e', 'l', 'o']

Use keywords to update specific node attributes for every node.

>>> G.add_nodes_from([1, 2], size=10)


>>> G.add_nodes_from([3, 4], weight=0.4)

Use (node, attrdict) tuples to update attributes for specific nodes.

>>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})])


>>> [Link][1]["size"]
11
>>> H = [Link]()
>>> H.add_nodes_from([Link](data=True))
>>> [Link][1]["size"]
11

[Link].remove_node

MultiGraph.remove_node(n)
Remove node n.
Removes the node n and all adjacent edges. Attempting to remove a non-existent node will raise an exception.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
remove_nodes_from()

76 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Examples

>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> list([Link])
[(0, 1), (1, 2)]
>>> G.remove_node(1)
>>> list([Link])
[]

[Link].remove_nodes_from

MultiGraph.remove_nodes_from(nodes)
Remove multiple nodes.
Parameters nodes (iterable container) – A container of nodes (list, dict, set, etc.). If a node in the
container is not in the graph it is silently ignored.
See also:
remove_node()

Examples

>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> e = list([Link])
>>> e
[0, 1, 2]
>>> G.remove_nodes_from(e)
>>> list([Link])
[]

[Link].add_edge

MultiGraph.add_edge(u_for_edge, v_for_edge, key=None, **attr)


Add an edge between u and v.
The nodes u and v will be automatically added if they are not already in the graph.
Edge attributes can be specified with keywords or by directly accessing the edge’s attribute dictionary. See
examples below.
Parameters
• u_for_edge, v_for_edge (nodes) – Nodes can be, for example, strings or numbers. Nodes
must be hashable (and not None) Python objects.
• key (hashable identifier, optional (default=lowest unused integer)) – Used to distinguish
multiedges between a pair of nodes.
• attr (keyword arguments, optional) – Edge data (or labels or objects) can be assigned using
keyword arguments.
Returns
Return type The edge key assigned to the edge.
See also:

2.2. Basic graph types 77


NetworkX Reference, Release 2.5

add_edges_from() add a collection of edges

Notes

To replace/update edge data, use the optional key argument to identify a unique edge. Otherwise a new edge
will be created.
NetworkX algorithms designed for weighted graphs cannot use multigraphs directly because it is not clear
how to handle multiedge weights. Convert to Graph using edge attribute ‘weight’ to enable weighted graph
algorithms.
Default keys are generated using the method new_edge_key(). This method can be overridden by subclass-
ing the base class and providing a custom new_edge_key() method.

Examples

The following all add the edge e=(1, 2) to graph G:

>>> G = [Link]()
>>> e = (1, 2)
>>> ekey = G.add_edge(1, 2) # explicit two-node form
>>> G.add_edge(*e) # single edge as tuple of two nodes
1
>>> G.add_edges_from([(1, 2)]) # add edges from iterable container
[2]

Associate data to edges using keywords:

>>> ekey = G.add_edge(1, 2, weight=3)


>>> ekey = G.add_edge(1, 2, key=0, weight=4) # update data for key=0
>>> ekey = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)

For non-string attribute keys, use subscript notation.

>>> ekey = G.add_edge(1, 2)


>>> G[1][2][0].update({0: 5})
>>> [Link][1, 2, 0].update({0: 5})

[Link].add_edges_from

MultiGraph.add_edges_from(ebunch_to_add, **attr)
Add all the edges in ebunch_to_add.
Parameters
• ebunch_to_add (container of edges) – Each edge given in the container will be added to
the graph. The edges can be:
– 2-tuples (u, v) or
– 3-tuples (u, v, d) for an edge data dict d, or
– 3-tuples (u, v, k) for not iterable key k, or
– 4-tuples (u, v, k, d) for an edge with data and key k

78 Chapter 2. Graph types


NetworkX Reference, Release 2.5

• attr (keyword arguments, optional) – Edge data (or labels or objects) can be assigned using
keyword arguments.
Returns
Return type A list of edge keys assigned to the edges in ebunch.
See also:

add_edge() add a single edge


add_weighted_edges_from() convenient way to add weighted edges

Notes

Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added.
Edge attributes specified in an ebunch take precedence over attributes specified via keyword arguments.
Default keys are generated using the method new_edge_key(). This method can be overridden by subclass-
ing the base class and providing a custom new_edge_key() method.

Examples

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
>>> e = zip(range(0, 3), range(1, 4))
>>> G.add_edges_from(e) # Add the path graph 0-1-2-3

Associate data to edges

>>> G.add_edges_from([(1, 2), (2, 3)], weight=3)


>>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")

[Link].add_weighted_edges_from

MultiGraph.add_weighted_edges_from(ebunch_to_add, weight='weight', **attr)


Add weighted edges in ebunch_to_add with specified weight attr
Parameters
• ebunch_to_add (container of edges) – Each edge given in the list or container will be added
to the graph. The edges must be given as 3-tuples (u, v, w) where w is a number.
• weight (string, optional (default= ‘weight’)) – The attribute name for the edge weights to
be added.
• attr (keyword arguments, optional (default= no attributes)) – Edge attributes to add/update
for all edges.
See also:

add_edge() add a single edge


add_edges_from() add multiple edges

2.2. Basic graph types 79


NetworkX Reference, Release 2.5

Notes

Adding the same edge twice for Graph/DiGraph simply updates the edge data. For MultiGraph/MultiDiGraph,
duplicate edges are stored.

Examples

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_weighted_edges_from([(0, 1, 3.0), (1, 2, 7.5)])

[Link].new_edge_key

MultiGraph.new_edge_key(u, v)
Returns an unused key for edges between nodes u and v.
The nodes u and v do not need to be already in the graph.

Notes

In the standard MultiGraph class the new key is the number of existing edges between u and v (increased
if necessary to ensure unused). The first edge will have key 0, then 1, etc. If an edge is removed further
new_edge_keys may not be in this order.
Parameters u, v (nodes)
Returns key
Return type int

[Link].remove_edge

MultiGraph.remove_edge(u, v, key=None)
Remove an edge between u and v.
Parameters
• u, v (nodes) – Remove an edge between nodes u and v.
• key (hashable identifier, optional (default=None)) – Used to distinguish multiple edges be-
tween a pair of nodes. If None remove a single (arbitrary) edge between u and v.
Raises NetworkXError – If there is not an edge between u and v, or if there is no edge with the
specified key.
See also:

remove_edges_from() remove a collection of edges

80 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Examples

>>> G = [Link]()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.remove_edge(0, 1)
>>> e = (1, 2)
>>> G.remove_edge(*e) # unpacks e from an edge tuple

For multiple edges

>>> G = [Link]() # or MultiDiGraph, etc


>>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned
[0, 1, 2]
>>> G.remove_edge(1, 2) # remove a single (arbitrary) edge

For edges with keys

>>> G = [Link]() # or MultiDiGraph, etc


>>> G.add_edge(1, 2, key="first")
'first'
>>> G.add_edge(1, 2, key="second")
'second'
>>> G.remove_edge(1, 2, key="second")

[Link].remove_edges_from

MultiGraph.remove_edges_from(ebunch)
Remove all edges specified in ebunch.
Parameters ebunch (list or container of edge tuples) – Each edge given in the list or container will
be removed from the graph. The edges can be:
• 2-tuples (u, v) All edges between u and v are removed.
• 3-tuples (u, v, key) The edge identified by key is removed.
• 4-tuples (u, v, key, data) where data is ignored.
See also:

remove_edge() remove a single edge

Notes

Will fail silently if an edge in ebunch is not in the graph.

2.2. Basic graph types 81


NetworkX Reference, Release 2.5

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> ebunch = [(1, 2), (2, 3)]
>>> G.remove_edges_from(ebunch)

Removing multiple copies of edges

>>> G = [Link]()
>>> keys = G.add_edges_from([(1, 2), (1, 2), (1, 2)])
>>> G.remove_edges_from([(1, 2), (1, 2)])
>>> list([Link]())
[(1, 2)]
>>> G.remove_edges_from([(1, 2), (1, 2)]) # silently ignore extra copy
>>> list([Link]) # now empty graph
[]

[Link]

[Link](edges=None, nodes=None)
Update the graph using nodes/edges/graphs as input.
Like [Link], this method takes a graph as input, adding the graph’s nodes and edges to this graph. It can
also take two inputs: edges and nodes. Finally it can take either edges or nodes. To specify only nodes the
keyword nodes must be used.
The collections of edges and nodes are treated similarly to the add_edges_from/add_nodes_from methods.
When iterated, they should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
Parameters
• edges (Graph object, collection of edges, or None) – The first parameter can be a graph or
some edges. If it has attributes nodes and edges, then it is taken to be a Graph-like object
and those attributes are used as collections of nodes and edges to be added to the graph. If
the first parameter does not have those attributes, it is treated as a collection of edges and
added to the graph. If the first argument is None, no edges are added.
• nodes (collection of nodes, or None) – The second parameter is treated as a collection of
nodes to be added to the graph unless it is None. If edges is None and nodes is
None an exception is raised. If the first parameter is a Graph, then nodes is ignored.

Examples

>>> G = nx.path_graph(5)
>>> [Link](nx.complete_graph(range(4, 10)))
>>> from itertools import combinations
>>> edges = (
... (u, v, {"power": u * v})
... for u, v in combinations(range(10, 20), 2)
... if u * v < 225
... )
>>> nodes = [1000] # for singleton, use a container
>>> [Link](edges, nodes)

82 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Notes

It you want to update the graph using an adjacency structure it is straightforward to obtain the edges/nodes from
adjacency. The following examples provide common cases, your adjacency may be slightly different and require
tweaks of these examples.

>>> # dict-of-set/list/tuple
>>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}}
>>> e = [(u, v) for u, nbrs in [Link]() for v in nbrs]
>>> [Link](edges=e, nodes=adj)

>>> DG = [Link]()
>>> # dict-of-dict-of-attribute
>>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}}
>>> e = [
... (u, v, {"weight": d})
... for u, nbrs in [Link]()
... for v, d in [Link]()
... ]
>>> [Link](edges=e, nodes=adj)

>>> # dict-of-dict-of-dict
>>> adj = {1: {2: {"weight": 1.3}, 3: {"color": 0.7, "weight": 1.2}}}
>>> e = [
... (u, v, {"weight": d})
... for u, nbrs in [Link]()
... for v, d in [Link]()
... ]
>>> [Link](edges=e, nodes=adj)

>>> # predecessor adjacency (dict-of-set)


>>> pred = {1: {2, 3}, 2: {3}, 3: {3}}
>>> e = [(v, u) for u, nbrs in [Link]() for v in nbrs]

>>> # MultiGraph dict-of-dict-of-dict-of-attribute


>>> MDG = [Link]()
>>> adj = {
... 1: {2: {0: {"weight": 1.3}, 1: {"weight": 1.2}}},
... 3: {2: {0: {"weight": 0.7}}},
... }
>>> e = [
... (u, v, ekey, d)
... for u, nbrs in [Link]()
... for v, keydict in [Link]()
... for ekey, d in [Link]()
... ]
>>> [Link](edges=e)

See also:

add_edges_from() add multiple edges to a graph


add_nodes_from() add multiple nodes to a graph

2.2. Basic graph types 83


NetworkX Reference, Release 2.5

[Link]

[Link]()
Remove all nodes and edges from the graph.
This also removes the name, and all graph, node, and edge attributes.

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [Link]()
>>> list([Link])
[]
>>> list([Link])
[]

[Link].clear_edges

MultiGraph.clear_edges()
Remove all edges from the graph without altering nodes.

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.clear_edges()
>>> list([Link])
[0, 1, 2, 3]
>>> list([Link])
[]

Reporting nodes edges and neighbors

[Link] A NodeView of the Graph as [Link] or [Link]().


MultiGraph.__iter__() Iterate over the nodes.
MultiGraph.has_node(n) Returns True if the graph contains the node n.
MultiGraph.__contains__(n) Returns True if n is a node, False otherwise.
[Link] Returns an iterator over the edges.
MultiGraph.has_edge(u, v[, key]) Returns True if the graph has an edge between nodes u
and v.
MultiGraph.get_edge_data(u, v[, key, default]) Returns the attribute dictionary associated with edge (u,
v).
[Link](n) Returns an iterator over all neighbors of node n.
[Link] Graph adjacency object holding the neighbors of each
node.
MultiGraph.__getitem__(n) Returns a dict of neighbors of node n.
[Link]() Returns an iterator over (node, adjacency dict) tuples for
all nodes.
continues on next page

84 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Table 10 – continued from previous page


MultiGraph.nbunch_iter([nbunch]) Returns an iterator over nodes contained in nbunch that
are also in the graph.

[Link]

property [Link]
A NodeView of the Graph as [Link] or [Link]().
Can be used as [Link] for data lookup and for set-like operations. Can also be used as G.
nodes(data='color', default=None) to return a NodeDataView which reports specific node data
but no set operations. It presents a dict-like interface as well with [Link]() iterating over (node,
nodedata) 2-tuples and [Link][3]['foo'] providing the value of the foo attribute for node 3. In
addition, a view [Link]('foo') provides a dict-like interface to the foo attribute of each node.
[Link]('foo', default=1) provides a default for nodes that do not have attribute foo.
Parameters
• data (string or bool, optional (default=False)) – The node attribute returned in 2-tuple (n,
ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the
nodes n.
• default (value, optional (default=None)) – Value used for nodes that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns
Allows set-like operations over the nodes as well as node attribute dict lookup and calling to
get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A
NodeView iterates over n and includes set operations.
When called, if data is False, an iterator over nodes. Otherwise an iterator of 2-tuples (node,
attribute value) where the attribute is specified in data. If data is True then the attribute becomes
the entire data dictionary.
Return type NodeView

Notes

If your node data is not needed, it is simpler and equivalent to use the expression for n in G, or list(G).

Examples

There are two simple ways of getting a list of all nodes in the graph:

>>> G = nx.path_graph(3)
>>> list([Link])
[0, 1, 2]
>>> list(G)
[0, 1, 2]

To get the node data along with the nodes:

2.2. Basic graph types 85


NetworkX Reference, Release 2.5

>>> G.add_node(1, time="5pm")


>>> [Link][0]["foo"] = "bar"
>>> list([Link](data=True))
[(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
>>> list([Link]())
[(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]

>>> list([Link](data="foo"))
[(0, 'bar'), (1, None), (2, None)]
>>> list([Link]("foo"))
[(0, 'bar'), (1, None), (2, None)]

>>> list([Link](data="time"))
[(0, None), (1, '5pm'), (2, None)]
>>> list([Link]("time"))
[(0, None), (1, '5pm'), (2, None)]

>>> list([Link](data="time", default="Not Available"))


[(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
>>> list([Link]("time", default="Not Available"))
[(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]

If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create
a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never
None:

>>> G = [Link]()
>>> G.add_node(0)
>>> G.add_node(1, weight=2)
>>> G.add_node(2, weight=3)
>>> dict([Link](data="weight", default=1))
{0: 1, 1: 2, 2: 3}

[Link].__iter__

MultiGraph.__iter__()
Iterate over the nodes. Use: ‘for n in G’.
Returns niter – An iterator over all nodes in the graph.
Return type iterator

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [n for n in G]
[0, 1, 2, 3]
>>> list(G)
[0, 1, 2, 3]

86 Chapter 2. Graph types


NetworkX Reference, Release 2.5

[Link].has_node

MultiGraph.has_node(n)
Returns True if the graph contains the node n.
Identical to n in G
Parameters n (node)

Examples

>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.has_node(0)
True

It is more readable and simpler to use


>>> 0 in G
True

[Link].__contains__

MultiGraph.__contains__(n)
Returns True if n is a node, False otherwise. Use: ‘n in G’.

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> 1 in G
True

[Link]

property [Link]
Returns an iterator over the edges.
edges(self, nbunch=None, data=False, keys=False, default=None)
The EdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called,
it also provides an EdgeDataView object which allows control of access to edge attributes (but does not pro-
vide set-like operations). Hence, [Link][u, v]['color'] provides the value of the color attribute for
edge (u, v) while for (u, v, c) in [Link](data='color', default='red'): iterates
through all the edges yielding the color attribute.
Edges are returned as tuples with optional data and keys in the order (node, neighbor, key, data).
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).

2.2. Basic graph types 87


NetworkX Reference, Release 2.5

• keys (bool, optional (default=False)) – If True, return edge keys with each edge.
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns edges – A view of edge attributes, usually it iterates over (u, v) (u, v, k) or (u, v, k, d) tuples
of edges, but can also be used for attribute lookup as edges[u, v, k]['foo'].
Return type MultiEdgeView

Notes

Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.

Examples

>>> G = [Link]() # or MultiDiGraph


>>> nx.add_path(G, [0, 1, 2])
>>> key = G.add_edge(2, 3, weight=5)
>>> [e for e in [Link]()]
[(0, 1), (1, 2), (2, 3)]
>>> [Link]() # default data is {} (empty dict)
MultiEdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
>>> [Link]("weight", default=1)
MultiEdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
>>> [Link](keys=True) # default keys are integers
MultiEdgeView([(0, 1, 0), (1, 2, 0), (2, 3, 0)])
>>> [Link](keys=True)
MultiEdgeDataView([(0, 1, 0, {}), (1, 2, 0, {}), (2, 3, 0, {'weight': 5})])
>>> [Link]("weight", default=1, keys=True)
MultiEdgeDataView([(0, 1, 0, 1), (1, 2, 0, 1), (2, 3, 0, 5)])
>>> [Link]([0, 3])
MultiEdgeDataView([(0, 1), (3, 2)])
>>> [Link](0)
MultiEdgeDataView([(0, 1)])

[Link].has_edge

MultiGraph.has_edge(u, v, key=None)
Returns True if the graph has an edge between nodes u and v.
This is the same as v in G[u] or key in G[u][v] without KeyError exceptions.
Parameters
• u, v (nodes) – Nodes can be, for example, strings or numbers.
• key (hashable identifier, optional (default=None)) – If specified return True only if the edge
with key is found.
Returns edge_ind – True if edge is in the graph, False otherwise.
Return type bool

88 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Examples

Can be called either using two nodes u, v, an edge tuple (u, v), or an edge tuple (u, v, key).

>>> G = [Link]() # or MultiDiGraph


>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.has_edge(0, 1) # using two nodes
True
>>> e = (0, 1)
>>> G.has_edge(*e) # e is a 2-tuple (u, v)
True
>>> G.add_edge(0, 1, key="a")
'a'
>>> G.has_edge(0, 1, key="a") # specify key
True
>>> e = (0, 1, "a")
>>> G.has_edge(*e) # e is a 3-tuple (u, v, 'a')
True

The following syntax are equivalent:

>>> G.has_edge(0, 1)
True
>>> 1 in G[0] # though this gives :exc:`KeyError` if 0 not in G
True

[Link].get_edge_data

MultiGraph.get_edge_data(u, v, key=None, default=None)


Returns the attribute dictionary associated with edge (u, v).
This is identical to G[u][v][key] except the default is returned instead of an exception is the edge doesn’t
exist.
Parameters
• u, v (nodes)
• default (any Python object (default=None)) – Value to return if the edge (u, v) is not found.
• key (hashable identifier, optional (default=None)) – Return data only for the edge with
specified key.
Returns edge_dict – The edge attribute dictionary.
Return type dictionary

Examples

>>> G = [Link]() # or MultiDiGraph


>>> key = G.add_edge(0, 1, key="a", weight=7)
>>> G[0][1]["a"] # key='a'
{'weight': 7}
>>> [Link][0, 1, "a"] # key='a'
{'weight': 7}

2.2. Basic graph types 89


NetworkX Reference, Release 2.5

Warning: we protect the graph data structure by making [Link] and G[1][2] read-only dict-like structures.
However, you can assign values to attributes in e.g. [Link][1, 2, 'a'] or G[1][2]['a'] using an
additional bracket as shown next. You need to specify all edge info to assign to the edge data associated with an
edge.

>>> G[0][1]["a"]["weight"] = 10
>>> [Link][0, 1, "a"]["weight"] = 10
>>> G[0][1]["a"]["weight"]
10
>>> [Link][1, 0, "a"]["weight"]
10

>>> G = [Link]() # or MultiDiGraph


>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.get_edge_data(0, 1)
{0: {}}
>>> e = (0, 1)
>>> G.get_edge_data(*e) # tuple form
{0: {}}
>>> G.get_edge_data("a", "b", default=0) # edge not in graph, return 0
0

[Link]

[Link](n)
Returns an iterator over all neighbors of node n.
This is identical to iter(G[n])
Parameters n (node) – A node in the graph
Returns neighbors – An iterator over all neighbors of node n
Return type iterator
Raises NetworkXError – If the node n is not in the graph.

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [n for n in [Link](0)]
[1]

Notes

Alternate ways to access the neighbors are [Link][n] or G[n]:

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_edge("a", "b", weight=7)
>>> G["a"]
AtlasView({'b': {'weight': 7}})
>>> G = nx.path_graph(4)
>>> [n for n in G[0]]
[1]

90 Chapter 2. Graph types


NetworkX Reference, Release 2.5

[Link]

property [Link]
Graph adjacency object holding the neighbors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed
by neighbor to the edgekey-data-dict. So [Link][3][2][0]['color'] = 'blue' sets the color of the
edge (3, 2, 0) to "blue".
Iterating over [Link] behaves like a dict. Useful idioms include for nbr, nbrdict in [Link][n].
items():.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in
G[node].data('foo', default=1): works.
For directed graphs, [Link] holds outgoing (successor) info.

[Link].__getitem__

MultiGraph.__getitem__(n)
Returns a dict of neighbors of node n. Use: ‘G[n]’.
Parameters n (node) – A node in the graph.
Returns adj_dict – The adjacency dictionary for nodes connected to n.
Return type dictionary

Notes

G[n] is the same as [Link][n] and similar to [Link](n) (which is an iterator over [Link][n])

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G[0]
AtlasView({1: {}})

[Link]

[Link]()
Returns an iterator over (node, adjacency dict) tuples for all nodes.
For directed graphs, only outgoing neighbors/adjacencies are included.
Returns adj_iter – An iterator over (node, adjacency dictionary) for all nodes in the graph.
Return type iterator

2.2. Basic graph types 91


NetworkX Reference, Release 2.5

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [(n, nbrdict) for n, nbrdict in [Link]()]
[(0, {1: {}}), (1, {0: {}, 2: {}}), (2, {1: {}, 3: {}}), (3, {2: {}})]

[Link].nbunch_iter

MultiGraph.nbunch_iter(nbunch=None)
Returns an iterator over nodes contained in nbunch that are also in the graph.
The nodes in nbunch are checked for membership in the graph and if not are silently ignored.
Parameters nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
Returns niter – An iterator over nodes in nbunch that are also in the graph. If nbunch is None,
iterate over all nodes in the graph.
Return type iterator
Raises NetworkXError – If nbunch is not a node or or sequence of nodes. If a node in nbunch is
not hashable.
See also:
Graph.__iter__()

Notes

When nbunch is an iterator, the returned iterator yields values directly from nbunch, becoming exhausted when
nbunch is exhausted.
To test whether nbunch is a single node, one can use “if nbunch in self:”, even after processing with this routine.
If nbunch is not a node or a (possibly empty) sequence/iterator or None, a NetworkXError is raised. Also, if
any object in nbunch is not hashable, a NetworkXError is raised.

Counting nodes edges and neighbors

[Link]() Returns the number of nodes in the graph.


MultiGraph.number_of_nodes() Returns the number of nodes in the graph.
MultiGraph.__len__() Returns the number of nodes in the graph.
[Link] A DegreeView for the Graph as [Link] or [Link]().
[Link]([weight]) Returns the number of edges or total of all edge weights.
MultiGraph.number_of_edges([u, v]) Returns the number of edges between two nodes.

92 Chapter 2. Graph types


NetworkX Reference, Release 2.5

[Link]

[Link]()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
number_of_nodes(), __len__()

Examples

>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [Link]()
3

[Link].number_of_nodes

MultiGraph.number_of_nodes()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
order(), __len__()

Examples

>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.number_of_nodes()
3

[Link].__len__

MultiGraph.__len__()
Returns the number of nodes in the graph. Use: ‘len(G)’.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
number_of_nodes(), order()

2.2. Basic graph types 93


NetworkX Reference, Release 2.5

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> len(G)
4

[Link]

property [Link]
A DegreeView for the Graph as [Link] or [Link]().
The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge
weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The name of an edge attribute that holds
the numerical value used as a weight. If None, then each edge has weight 1. The degree is
the sum of the edge weights adjacent to the node.
Returns
• If a single node is requested
• deg (int) – Degree of the node, if a single node is passed as argument.
• OR if multiple nodes are requested
• nd_iter (iterator) – The iterator returns two-tuples of (node, degree).

Examples

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> nx.add_path(G, [0, 1, 2, 3])
>>> [Link](0) # node 0 with degree 1
1
>>> list([Link]([0, 1]))
[(0, 1), (1, 2)]

[Link]

[Link](weight=None)
Returns the number of edges or total of all edge weights.
Parameters weight (string or None, optional (default=None)) – The edge attribute that holds the
numerical value used as a weight. If None, then each edge has weight 1.
Returns
size – The number of edges or (if weight keyword is provided) the total weight sum.
If weight is None, returns an int. Otherwise a float (or more general numeric if the weights are
more general).

94 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Return type numeric


See also:
number_of_edges()

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [Link]()
3

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_edge("a", "b", weight=2)
>>> G.add_edge("b", "c", weight=4)
>>> [Link]()
2
>>> [Link](weight="weight")
6.0

[Link].number_of_edges

MultiGraph.number_of_edges(u=None, v=None)
Returns the number of edges between two nodes.
Parameters u, v (nodes, optional (Gefault=all edges)) – If u and v are specified, return the number
of edges between u and v. Otherwise return the total number of all edges.
Returns nedges – The number of edges in the graph. If nodes u and v are specified return the
number of edges between those nodes. If the graph is directed, this only returns the number of
edges from u to v.
Return type int
See also:
size()

Examples

For undirected multigraphs, this method counts the total number of edges in the graph:

>>> G = [Link]()
>>> G.add_edges_from([(0, 1), (0, 1), (1, 2)])
[0, 1, 0]
>>> G.number_of_edges()
3

If you specify two nodes, this counts the total number of edges joining the two nodes:

>>> G.number_of_edges(0, 1)
2

For directed multigraphs, this method can count the total number of directed edges from u to v:

2.2. Basic graph types 95


NetworkX Reference, Release 2.5

>>> G = [Link]()
>>> G.add_edges_from([(0, 1), (0, 1), (1, 0)])
[0, 1, 0]
>>> G.number_of_edges(0, 1)
2
>>> G.number_of_edges(1, 0)
1

Making copies and subgraphs

[Link]([as_view]) Returns a copy of the graph.


MultiGraph.to_undirected([as_view]) Returns an undirected copy of the graph.
MultiGraph.to_directed([as_view]) Returns a directed representation of the graph.
[Link](nodes) Returns a SubGraph view of the subgraph induced on
nodes.
MultiGraph.edge_subgraph(edges) Returns the subgraph induced by the specified edges.

[Link]

[Link](as_view=False)
Returns a copy of the graph.
The copy method by default returns an independent shallow copy of the graph and attributes. That is, if an
attribute is a container, that container is shared by the original an the copy. Use Python’s [Link] for
new containers.
If as_view is True then a view is returned instead of a copy.

Notes

All copies reproduce the graph structure, but data attributes may be handled in different ways. There are four
types of copies of a graph that people might want.
Deepcopy – A “deepcopy” copies the graph structure as well as all data attributes and any objects they might
contain. The entire graph object is new so that changes in the copy do not affect the original object. (see Python’s
[Link])
Data Reference (Shallow) – For a shallow copy the graph structure is copied but the edge, node and graph at-
tribute dicts are references to those in the original graph. This saves time and memory but could cause confusion
if you change an attribute in one graph and it changes the attribute in the other. NetworkX does not provide this
level of shallow copy.
Independent Shallow – This copy creates new independent attribute dicts and then does a shallow copy of the
attributes. That is, any attributes that are containers are shared between the new graph and the original. This is
exactly what [Link]() provides. You can obtain this style copy using:

>>> G = nx.path_graph(5)
>>> H = [Link]()
>>> H = [Link](as_view=False)
>>> H = [Link](G)
>>> H = G.__class__(G)

96 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Fresh Data – For fresh data, the graph structure is copied while new empty data attribute dicts are created. The
resulting graph is independent of the original and it has no edge, node or graph attributes. Fresh copies are not
enabled. Instead use:

>>> H = G.__class__()
>>> H.add_nodes_from(G)
>>> H.add_edges_from([Link])

View – Inspired by dict-views, graph-views act like read-only versions of the original graph, providing a copy
of the original structure without requiring any memory for copying the information.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Parameters as_view (bool, optional (default=False)) – If True, the returned graph-view provides a
read-only view of the original graph without actually copying any data.
Returns G – A copy of the graph.
Return type Graph
See also:

to_directed() return a directed copy of the graph.

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> H = [Link]()

[Link].to_undirected

MultiGraph.to_undirected(as_view=False)
Returns an undirected copy of the graph.
Returns G – A deepcopy of the graph.
Return type Graph/MultiGraph
See also:
copy(), add_edge(), add_edges_from()

Notes

This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar G = [Link](D) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Warning: If you have subclassed MultiiGraph to use dict-like objects in the data structure, those changes do not
transfer to the MultiGraph created by this method.

2.2. Basic graph types 97


NetworkX Reference, Release 2.5

Examples

>>> G = nx.path_graph(2) # or MultiGraph, etc


>>> H = G.to_directed()
>>> list([Link])
[(0, 1), (1, 0)]
>>> G2 = H.to_undirected()
>>> list([Link])
[(0, 1)]

[Link].to_directed

MultiGraph.to_directed(as_view=False)
Returns a directed representation of the graph.
Returns G – A directed graph with the same name, same nodes, and with each edge (u, v, data)
replaced by two directed edges (u, v, data) and (v, u, data).
Return type MultiDiGraph

Notes

This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar D=DiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Warning: If you have subclassed MultiGraph to use dict-like objects in the data structure, those changes do not
transfer to the MultiDiGraph created by this method.

Examples

>>> G = [Link]() # or MultiGraph, etc


>>> G.add_edge(0, 1)
>>> H = G.to_directed()
>>> list([Link])
[(0, 1), (1, 0)]

If already directed, return a (deep) copy

>>> G = [Link]() # or MultiDiGraph, etc


>>> G.add_edge(0, 1)
>>> H = G.to_directed()
>>> list([Link])
[(0, 1)]

98 Chapter 2. Graph types


NetworkX Reference, Release 2.5

[Link]

[Link](nodes)
Returns a SubGraph view of the subgraph induced on nodes.
The induced subgraph of the graph contains the nodes in nodes and the edges between those nodes.
Parameters nodes (list, iterable) – A container of nodes which will be iterated through once.
Returns G – A subgraph view of the graph. The graph structure cannot be changed but node/edge
attributes can and are shared with the original graph.
Return type SubGraph View

Notes

The graph, edge and node attributes are shared with the original graph. Changes to the graph structure is ruled
out by the view, but changes to attributes are reflected in the original graph.
To create a subgraph with its own copy of the edge/node attributes use: [Link](nodes).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(nodes)])
Subgraph views are sometimes NOT what you want. In most cases where you want to do more than simply look
at the induced edges, it makes more sense to just create the subgraph as its own graph with code like:

# Create a subgraph SG based on a (possibly multigraph) G


SG = G.__class__()
SG.add_nodes_from((n, [Link][n]) for n in largest_wcc)
if SG.is_multigraph():
SG.add_edges_from((n, nbr, key, d)
for n, nbrs in [Link]() if n in largest_wcc
for nbr, keydict in [Link]() if nbr in largest_wcc
for key, d in [Link]())
else:
SG.add_edges_from((n, nbr, d)
for n, nbrs in [Link]() if n in largest_wcc
for nbr, d in [Link]() if nbr in largest_wcc)
[Link]([Link])

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> H = [Link]([0, 1, 2])
>>> list([Link])
[(0, 1), (1, 2)]

2.2. Basic graph types 99


NetworkX Reference, Release 2.5

[Link].edge_subgraph

MultiGraph.edge_subgraph(edges)
Returns the subgraph induced by the specified edges.
The induced subgraph contains each edge in edges and each node incident to any one of those edges.
Parameters edges (iterable) – An iterable of edges in this graph.
Returns G – An edge-induced subgraph of this 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()

Examples

>>> G = nx.path_graph(5)
>>> H = G.edge_subgraph([(0, 1), (3, 4)])
>>> list([Link])
[0, 1, 3, 4]
>>> list([Link])
[(0, 1), (3, 4)]

2.2.4 MultiDiGraph—Directed graphs with self loops and parallel edges

Overview

class MultiDiGraph(incoming_graph_data=None, **attr)


A directed graph class that can store multiedges.
Multiedges are multiple edges between two nodes. Each edge can hold optional data or attributes.
A MultiDiGraph holds directed edges. Self loops are allowed.
Nodes can be arbitrary (hashable) Python objects with optional key/value attributes. By convention None is not
used as a node.
Edges are represented as links between nodes with optional key/value attributes.
Parameters
• incoming_graph_data (input graph (optional, default: None)) – Data to initialize graph. If
None (default) an empty graph is created. The data can be any format that is supported by
the to_networkx_graph() function, currently including edge list, dict of dicts, dict of lists,
NetworkX graph, NumPy matrix or 2d ndarray, SciPy sparse matrix, or PyGraphviz graph.
• attr (keyword arguments, optional (default= no attributes)) – Attributes to add to graph as
key=value pairs.

100 Chapter 2. Graph types


NetworkX Reference, Release 2.5

See also:
Graph, DiGraph, MultiGraph, OrderedMultiDiGraph

Examples

Create an empty graph structure (a “null graph”) with no nodes and no edges.

>>> G = [Link]()

G can be grown in several ways.


Nodes:
Add one node at a time:

>>> G.add_node(1)

Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph).

>>> G.add_nodes_from([2, 3])


>>> G.add_nodes_from(range(100, 110))
>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)

In addition to strings and integers any hashable Python object (except None) can represent a node, e.g. a
customized node object, or even another Graph.

>>> G.add_node(H)

Edges:
G can also be grown by adding edges.
Add one edge,

>>> key = G.add_edge(1, 2)

a list of edges,

>>> keys = G.add_edges_from([(1, 2), (1, 3)])

or a collection of edges,

>>> keys = G.add_edges_from([Link])

If some edges connect nodes not yet in the graph, the nodes are added automatically. If an edge already exists,
an additional edge is created and stored using a key to identify the edge. By default the key is the lowest unused
integer.

>>> keys = G.add_edges_from([(4, 5, dict(route=282)), (4, 5, dict(route=37))])


>>> G[4]
AdjacencyView({5: {0: {}, 1: {'route': 282}, 2: {'route': 37}}})

Attributes:
Each graph, node, and edge can hold key/value attribute pairs in an associated attribute dictionary (the keys
must be hashable). By default these are empty, but can be added or changed using add_edge, add_node or direct
manipulation of the attribute dictionaries named graph, node and edge respectively.

2.2. Basic graph types 101


NetworkX Reference, Release 2.5

>>> G = [Link](day="Friday")
>>> [Link]
{'day': 'Friday'}

Add node attributes using add_node(), add_nodes_from() or [Link]

>>> G.add_node(1, time="5pm")


>>> G.add_nodes_from([3], time="2pm")
>>> [Link][1]
{'time': '5pm'}
>>> [Link][1]["room"] = 714
>>> del [Link][1]["room"] # remove attribute
>>> list([Link](data=True))
[(1, {'time': '5pm'}), (3, {'time': '2pm'})]

Add edge attributes using add_edge(), add_edges_from(), subscript notation, or [Link].

>>> key = G.add_edge(1, 2, weight=4.7)


>>> keys = G.add_edges_from([(3, 4), (4, 5)], color="red")
>>> keys = G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
>>> G[1][2][0]["weight"] = 4.7
>>> [Link][1, 2, 0]["weight"] = 4

Warning: we protect the graph data structure by making [Link][1, 2] a read-only dict-like structure.
However, you can assign to attributes in e.g. [Link][1, 2]. Thus, use 2 sets of brackets to add/change data
attributes: [Link][1, 2]['weight'] = 4 (For multigraphs: [Link][u, v, key][name] =
value).
Shortcuts:
Many common graph features allow python syntax to speed reporting.

>>> 1 in G # check if node in graph


True
>>> [n for n in G if n < 3] # iterate through nodes
[1, 2]
>>> len(G) # number of nodes in graph
5
>>> G[1] # adjacency dict-like view keyed by neighbor to edge attributes
AdjacencyView({2: {0: {'weight': 4}, 1: {'color': 'blue'}}})

Often the best way to traverse all edges of a graph is via the neighbors. The neighbors are available as an
adjacency-view [Link] object or via the method [Link]().

>>> for n, nbrsdict in [Link]():


... for nbr, keydict in [Link]():
... for key, eattr in [Link]():
... if "weight" in eattr:
... # Do something useful with the edges
... pass

But the edges() method is often more convenient:

>>> for u, v, keys, weight in [Link](data="weight", keys=True):


... if weight is not None:
... # Do something useful with the edges
... pass

102 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Reporting:
Simple graph information is obtained using methods and object-attributes. Reporting usually provides
views instead of containers to reduce memory usage. The views update as the graph is updated simi-
larly to dict-views. The objects nodes, `edges and adj provide access to data attributes via lookup
(e.g. nodes[n], `edges[u, v], adj[u][v]) and iteration (e.g. [Link](), nodes.
data('color'), [Link]('color', default='blue') and similarly for edges) Views exist
for nodes, edges, neighbors()/adj and degree.
For details on these and other miscellaneous methods, see below.
Subclasses (Advanced):
The MultiDiGraph class uses a dict-of-dict-of-dict-of-dict structure. The outer dict (node_dict) holds adjacency
information keyed by node. The next dict (adjlist_dict) represents the adjacency information and holds edge_key
dicts keyed by neighbor. The edge_key dict holds each edge_attr dict keyed by edge key. The inner dict
(edge_attr_dict) represents the edge data and holds edge attribute values keyed by attribute names.
Each of these four dicts in the dict-of-dict-of-dict-of-dict structure can be replaced by a user defined dict-like
object. In general, the dict-like features should be maintained but extra features can be added. To replace
one of the dicts create a new graph class by changing the class(!) variable holding the factory for that dict-
like structure. The variable names are node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory and graph_attr_dict_factory.
node_dict_factory [function, (default: dict)] Factory function to be used to create the dict containing node
attributes, keyed by node id. It should require no arguments and return a dict-like object
node_attr_dict_factory: function, (default: dict) Factory function to be used to create the node attribute dict
which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like
object
adjlist_outer_dict_factory [function, (default: dict)] Factory function to be used to create the outer-most dict
in the data structure that holds adjacency info keyed by node. It should require no arguments and return a
dict-like object.
adjlist_inner_dict_factory [function, (default: dict)] Factory function to be used to create the adjacency list
dict which holds multiedge key dicts keyed by neighbor. It should require no arguments and return a
dict-like object.
edge_key_dict_factory [function, (default: dict)] Factory function to be used to create the edge key dict which
holds edge data keyed by edge key. It should require no arguments and return a dict-like object.
edge_attr_dict_factory [function, (default: dict)] Factory function to be used to create the edge attribute dict
which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like
object.
graph_attr_dict_factory [function, (default: dict)] Factory function to be used to create the graph attribute
dict which holds attribute values keyed by attribute name. It should require no arguments and return a
dict-like object.
Typically, if your extension doesn’t impact the data structure all methods will inherited without issue except:
to_directed/to_undirected. By default these methods create a DiGraph/Graph class and you probably
want them to create your extension of a DiGraph/Graph. To facilitate this we define two class variables that you
can set in your subclass.
to_directed_class [callable, (default: DiGraph or MultiDiGraph)] Class to create a new graph structure in the
to_directed method. If None, a NetworkX class (DiGraph or MultiDiGraph) is used.
to_undirected_class [callable, (default: Graph or MultiGraph)] Class to create a new graph structure in the
to_undirected method. If None, a NetworkX class (Graph or MultiGraph) is used.

2.2. Basic graph types 103


NetworkX Reference, Release 2.5

Examples

Please see ordered for examples of creating graph subclasses by overwriting the base class dict with a
dictionary-like object.

Methods

Adding and Removing Nodes and Edges

MultiDiGraph.__init__([incoming_graph_data]) Initialize a graph with edges, name, or graph attributes.


MultiDiGraph.add_node(node_for_adding, Add a single node node_for_adding and update
**attr) node attributes.
MultiDiGraph.add_nodes_from(. . . ) Add multiple nodes.
MultiDiGraph.remove_node(n) Remove node n.
MultiDiGraph.remove_nodes_from(nodes) Remove multiple nodes.
MultiDiGraph.add_edge(u_for_edge, Add an edge between u and v.
v_for_edge)
MultiDiGraph.add_edges_from(ebunch_to_add, Add all the edges in ebunch_to_add.
...)
MultiDiGraph.add_weighted_edges_from(. . . [,Add weighted edges in ebunch_to_add with speci-
. . . ]) fied weight attr
MultiDiGraph.new_edge_key(u, v) Returns an unused key for edges between nodes u and
v.
MultiDiGraph.remove_edge(u, v[, key]) Remove an edge between u and v.
MultiDiGraph.remove_edges_from(ebunch) Remove all edges specified in ebunch.
[Link]([edges, nodes]) Update the graph using nodes/edges/graphs as input.
[Link]() Remove all nodes and edges from the graph.
MultiDiGraph.clear_edges() Remove all edges from the graph without altering
nodes.

[Link].__init__

MultiDiGraph.__init__(incoming_graph_data=None, **attr)
Initialize a graph with edges, name, or graph attributes.
Parameters
• incoming_graph_data (input graph) – Data to initialize graph. If incom-
ing_graph_data=None (default) an empty graph is created. The data can be an edge list,
or any NetworkX graph object. If the corresponding optional Python packages are installed
the data can also be a NumPy matrix or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz
graph.
• attr (keyword arguments, optional (default= no attributes)) – Attributes to add to graph as
key=value pairs.
See also:
convert()

104 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Examples

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G = [Link](name="my graph")
>>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
>>> G = [Link](e)

Arbitrary graph attribute pairs (key=value) may be assigned

>>> G = [Link](e, day="Friday")


>>> [Link]
{'day': 'Friday'}

[Link].add_node

MultiDiGraph.add_node(node_for_adding, **attr)
Add a single node node_for_adding and update node attributes.
Parameters
• node_for_adding (node) – A node can be any hashable Python object except None.
• attr (keyword arguments, optional) – Set or change node attributes using key=value.
See also:
add_nodes_from()

Examples

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_node(1)
>>> G.add_node("Hello")
>>> K3 = [Link]([(0, 1), (1, 2), (2, 0)])
>>> G.add_node(K3)
>>> G.number_of_nodes()
3

Use keywords set/change node attributes:

>>> G.add_node(1, size=10)


>>> G.add_node(3, weight=0.4, UTM=("13S", 382871, 3972649))

Notes

A hashable object is one that can be used as a key in a Python dictionary. This includes strings, numbers, tuples
of strings and numbers, etc.
On many platforms hashable items also include mutables such as NetworkX Graphs, though one should be
careful that the hash doesn’t change on mutables.

2.2. Basic graph types 105


NetworkX Reference, Release 2.5

[Link].add_nodes_from

MultiDiGraph.add_nodes_from(nodes_for_adding, **attr)
Add multiple nodes.
Parameters
• nodes_for_adding (iterable container) – A container of nodes (list, dict, set, etc.). OR A
container of (node, attribute dict) tuples. Node attributes are updated using the attribute dict.
• attr (keyword arguments, optional (default= no attributes)) – Update attributes for all nodes
in nodes. Node attributes specified in nodes as a tuple take precedence over attributes spec-
ified via keyword arguments.
See also:
add_node()

Examples

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_nodes_from("Hello")
>>> K3 = [Link]([(0, 1), (1, 2), (2, 0)])
>>> G.add_nodes_from(K3)
>>> sorted([Link](), key=str)
[0, 1, 2, 'H', 'e', 'l', 'o']

Use keywords to update specific node attributes for every node.

>>> G.add_nodes_from([1, 2], size=10)


>>> G.add_nodes_from([3, 4], weight=0.4)

Use (node, attrdict) tuples to update attributes for specific nodes.

>>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})])


>>> [Link][1]["size"]
11
>>> H = [Link]()
>>> H.add_nodes_from([Link](data=True))
>>> [Link][1]["size"]
11

[Link].remove_node

MultiDiGraph.remove_node(n)
Remove node n.
Removes the node n and all adjacent edges. Attempting to remove a non-existent node will raise an exception.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
remove_nodes_from()

106 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Examples

>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> list([Link])
[(0, 1), (1, 2)]
>>> G.remove_node(1)
>>> list([Link])
[]

[Link].remove_nodes_from

MultiDiGraph.remove_nodes_from(nodes)
Remove multiple nodes.
Parameters nodes (iterable container) – A container of nodes (list, dict, set, etc.). If a node in the
container is not in the graph it is silently ignored.
See also:
remove_node()

Examples

>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> e = list([Link])
>>> e
[0, 1, 2]
>>> G.remove_nodes_from(e)
>>> list([Link])
[]

[Link].add_edge

MultiDiGraph.add_edge(u_for_edge, v_for_edge, key=None, **attr)


Add an edge between u and v.
The nodes u and v will be automatically added if they are not already in the graph.
Edge attributes can be specified with keywords or by directly accessing the edge’s attribute dictionary. See
examples below.
Parameters
• u_for_edge, v_for_edge (nodes) – Nodes can be, for example, strings or numbers. Nodes
must be hashable (and not None) Python objects.
• key (hashable identifier, optional (default=lowest unused integer)) – Used to distinguish
multiedges between a pair of nodes.
• attr_dict (dictionary, optional (default= no attributes)) – Dictionary of edge attributes.
Key/value pairs will update existing data associated with the edge.
• attr (keyword arguments, optional) – Edge data (or labels or objects) can be assigned using
keyword arguments.
Returns

2.2. Basic graph types 107


NetworkX Reference, Release 2.5

Return type The edge key assigned to the edge.


See also:

add_edges_from() add a collection of edges

Notes

To replace/update edge data, use the optional key argument to identify a unique edge. Otherwise a new edge
will be created.
NetworkX algorithms designed for weighted graphs cannot use multigraphs directly because it is not clear
how to handle multiedge weights. Convert to Graph using edge attribute ‘weight’ to enable weighted graph
algorithms.
Default keys are generated using the method new_edge_key(). This method can be overridden by subclass-
ing the base class and providing a custom new_edge_key() method.

Examples

The following all add the edge e=(1, 2) to graph G:

>>> G = [Link]()
>>> e = (1, 2)
>>> key = G.add_edge(1, 2) # explicit two-node form
>>> G.add_edge(*e) # single edge as tuple of two nodes
1
>>> G.add_edges_from([(1, 2)]) # add edges from iterable container
[2]

Associate data to edges using keywords:

>>> key = G.add_edge(1, 2, weight=3)


>>> key = G.add_edge(1, 2, key=0, weight=4) # update data for key=0
>>> key = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)

For non-string attribute keys, use subscript notation.

>>> ekey = G.add_edge(1, 2)


>>> G[1][2][0].update({0: 5})
>>> [Link][1, 2, 0].update({0: 5})

[Link].add_edges_from

MultiDiGraph.add_edges_from(ebunch_to_add, **attr)
Add all the edges in ebunch_to_add.
Parameters
• ebunch_to_add (container of edges) – Each edge given in the container will be added to
the graph. The edges can be:
– 2-tuples (u, v) or
– 3-tuples (u, v, d) for an edge data dict d, or
– 3-tuples (u, v, k) for not iterable key k, or

108 Chapter 2. Graph types


NetworkX Reference, Release 2.5

– 4-tuples (u, v, k, d) for an edge with data and key k


• attr (keyword arguments, optional) – Edge data (or labels or objects) can be assigned using
keyword arguments.
Returns
Return type A list of edge keys assigned to the edges in ebunch.
See also:

add_edge() add a single edge


add_weighted_edges_from() convenient way to add weighted edges

Notes

Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added.
Edge attributes specified in an ebunch take precedence over attributes specified via keyword arguments.
Default keys are generated using the method new_edge_key(). This method can be overridden by subclass-
ing the base class and providing a custom new_edge_key() method.

Examples

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
>>> e = zip(range(0, 3), range(1, 4))
>>> G.add_edges_from(e) # Add the path graph 0-1-2-3

Associate data to edges

>>> G.add_edges_from([(1, 2), (2, 3)], weight=3)


>>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")

[Link].add_weighted_edges_from

MultiDiGraph.add_weighted_edges_from(ebunch_to_add, weight='weight', **attr)


Add weighted edges in ebunch_to_add with specified weight attr
Parameters
• ebunch_to_add (container of edges) – Each edge given in the list or container will be added
to the graph. The edges must be given as 3-tuples (u, v, w) where w is a number.
• weight (string, optional (default= ‘weight’)) – The attribute name for the edge weights to
be added.
• attr (keyword arguments, optional (default= no attributes)) – Edge attributes to add/update
for all edges.
See also:

add_edge() add a single edge


add_edges_from() add multiple edges

2.2. Basic graph types 109


NetworkX Reference, Release 2.5

Notes

Adding the same edge twice for Graph/DiGraph simply updates the edge data. For MultiGraph/MultiDiGraph,
duplicate edges are stored.

Examples

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_weighted_edges_from([(0, 1, 3.0), (1, 2, 7.5)])

[Link].new_edge_key

MultiDiGraph.new_edge_key(u, v)
Returns an unused key for edges between nodes u and v.
The nodes u and v do not need to be already in the graph.

Notes

In the standard MultiGraph class the new key is the number of existing edges between u and v (increased
if necessary to ensure unused). The first edge will have key 0, then 1, etc. If an edge is removed further
new_edge_keys may not be in this order.
Parameters u, v (nodes)
Returns key
Return type int

[Link].remove_edge

MultiDiGraph.remove_edge(u, v, key=None)
Remove an edge between u and v.
Parameters
• u, v (nodes) – Remove an edge between nodes u and v.
• key (hashable identifier, optional (default=None)) – Used to distinguish multiple edges be-
tween a pair of nodes. If None remove a single (arbitrary) edge between u and v.
Raises NetworkXError – If there is not an edge between u and v, or if there is no edge with the
specified key.
See also:

remove_edges_from() remove a collection of edges

110 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Examples

>>> G = [Link]()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.remove_edge(0, 1)
>>> e = (1, 2)
>>> G.remove_edge(*e) # unpacks e from an edge tuple

For multiple edges

>>> G = [Link]()
>>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned
[0, 1, 2]
>>> G.remove_edge(1, 2) # remove a single (arbitrary) edge

For edges with keys

>>> G = [Link]()
>>> G.add_edge(1, 2, key="first")
'first'
>>> G.add_edge(1, 2, key="second")
'second'
>>> G.remove_edge(1, 2, key="second")

[Link].remove_edges_from

MultiDiGraph.remove_edges_from(ebunch)
Remove all edges specified in ebunch.
Parameters ebunch (list or container of edge tuples) – Each edge given in the list or container will
be removed from the graph. The edges can be:
• 2-tuples (u, v) All edges between u and v are removed.
• 3-tuples (u, v, key) The edge identified by key is removed.
• 4-tuples (u, v, key, data) where data is ignored.
See also:

remove_edge() remove a single edge

Notes

Will fail silently if an edge in ebunch is not in the graph.

2.2. Basic graph types 111


NetworkX Reference, Release 2.5

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> ebunch = [(1, 2), (2, 3)]
>>> G.remove_edges_from(ebunch)

Removing multiple copies of edges

>>> G = [Link]()
>>> keys = G.add_edges_from([(1, 2), (1, 2), (1, 2)])
>>> G.remove_edges_from([(1, 2), (1, 2)])
>>> list([Link]())
[(1, 2)]
>>> G.remove_edges_from([(1, 2), (1, 2)]) # silently ignore extra copy
>>> list([Link]) # now empty graph
[]

[Link]

[Link](edges=None, nodes=None)
Update the graph using nodes/edges/graphs as input.
Like [Link], this method takes a graph as input, adding the graph’s nodes and edges to this graph. It can
also take two inputs: edges and nodes. Finally it can take either edges or nodes. To specify only nodes the
keyword nodes must be used.
The collections of edges and nodes are treated similarly to the add_edges_from/add_nodes_from methods.
When iterated, they should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
Parameters
• edges (Graph object, collection of edges, or None) – The first parameter can be a graph or
some edges. If it has attributes nodes and edges, then it is taken to be a Graph-like object
and those attributes are used as collections of nodes and edges to be added to the graph. If
the first parameter does not have those attributes, it is treated as a collection of edges and
added to the graph. If the first argument is None, no edges are added.
• nodes (collection of nodes, or None) – The second parameter is treated as a collection of
nodes to be added to the graph unless it is None. If edges is None and nodes is
None an exception is raised. If the first parameter is a Graph, then nodes is ignored.

Examples

>>> G = nx.path_graph(5)
>>> [Link](nx.complete_graph(range(4, 10)))
>>> from itertools import combinations
>>> edges = (
... (u, v, {"power": u * v})
... for u, v in combinations(range(10, 20), 2)
... if u * v < 225
... )
>>> nodes = [1000] # for singleton, use a container
>>> [Link](edges, nodes)

112 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Notes

It you want to update the graph using an adjacency structure it is straightforward to obtain the edges/nodes from
adjacency. The following examples provide common cases, your adjacency may be slightly different and require
tweaks of these examples.

>>> # dict-of-set/list/tuple
>>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}}
>>> e = [(u, v) for u, nbrs in [Link]() for v in nbrs]
>>> [Link](edges=e, nodes=adj)

>>> DG = [Link]()
>>> # dict-of-dict-of-attribute
>>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}}
>>> e = [
... (u, v, {"weight": d})
... for u, nbrs in [Link]()
... for v, d in [Link]()
... ]
>>> [Link](edges=e, nodes=adj)

>>> # dict-of-dict-of-dict
>>> adj = {1: {2: {"weight": 1.3}, 3: {"color": 0.7, "weight": 1.2}}}
>>> e = [
... (u, v, {"weight": d})
... for u, nbrs in [Link]()
... for v, d in [Link]()
... ]
>>> [Link](edges=e, nodes=adj)

>>> # predecessor adjacency (dict-of-set)


>>> pred = {1: {2, 3}, 2: {3}, 3: {3}}
>>> e = [(v, u) for u, nbrs in [Link]() for v in nbrs]

>>> # MultiGraph dict-of-dict-of-dict-of-attribute


>>> MDG = [Link]()
>>> adj = {
... 1: {2: {0: {"weight": 1.3}, 1: {"weight": 1.2}}},
... 3: {2: {0: {"weight": 0.7}}},
... }
>>> e = [
... (u, v, ekey, d)
... for u, nbrs in [Link]()
... for v, keydict in [Link]()
... for ekey, d in [Link]()
... ]
>>> [Link](edges=e)

See also:

add_edges_from() add multiple edges to a graph


add_nodes_from() add multiple nodes to a graph

2.2. Basic graph types 113


NetworkX Reference, Release 2.5

[Link]

[Link]()
Remove all nodes and edges from the graph.
This also removes the name, and all graph, node, and edge attributes.

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [Link]()
>>> list([Link])
[]
>>> list([Link])
[]

[Link].clear_edges

MultiDiGraph.clear_edges()
Remove all edges from the graph without altering nodes.

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.clear_edges()
>>> list([Link])
[0, 1, 2, 3]
>>> list([Link])
[]

Reporting nodes edges and neighbors

[Link] A NodeView of the Graph as [Link] or [Link]().


MultiDiGraph.__iter__() Iterate over the nodes.
MultiDiGraph.has_node(n) Returns True if the graph contains the node n.
MultiDiGraph.__contains__(n) Returns True if n is a node, False otherwise.
[Link] An OutMultiEdgeView of the Graph as [Link] or
[Link]().
MultiDiGraph.out_edges An OutMultiEdgeView of the Graph as [Link] or
[Link]().
MultiDiGraph.in_edges An InMultiEdgeView of the Graph as G.in_edges or
G.in_edges().
MultiDiGraph.has_edge(u, v[, key]) Returns True if the graph has an edge between nodes u
and v.
MultiDiGraph.get_edge_data(u, v[, key, de- Returns the attribute dictionary associated with edge (u,
fault]) v).
[Link](n) Returns an iterator over successor nodes of n.
continues on next page

114 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Table 14 – continued from previous page


[Link] Graph adjacency object holding the neighbors of each
node.
MultiDiGraph.__getitem__(n) Returns a dict of neighbors of node n.
[Link](n) Returns an iterator over successor nodes of n.
[Link] Graph adjacency object holding the successors of each
node.
[Link](n) Returns an iterator over predecessor nodes of n.
[Link] Graph adjacency object holding the successors of each
node.
[Link]() Returns an iterator over (node, adjacency dict) tuples for
all nodes.
MultiDiGraph.nbunch_iter([nbunch]) Returns an iterator over nodes contained in nbunch that
are also in the graph.

[Link]

property [Link]
A NodeView of the Graph as [Link] or [Link]().
Can be used as [Link] for data lookup and for set-like operations. Can also be used as G.
nodes(data='color', default=None) to return a NodeDataView which reports specific node data
but no set operations. It presents a dict-like interface as well with [Link]() iterating over (node,
nodedata) 2-tuples and [Link][3]['foo'] providing the value of the foo attribute for node 3. In
addition, a view [Link]('foo') provides a dict-like interface to the foo attribute of each node.
[Link]('foo', default=1) provides a default for nodes that do not have attribute foo.
Parameters
• data (string or bool, optional (default=False)) – The node attribute returned in 2-tuple (n,
ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the
nodes n.
• default (value, optional (default=None)) – Value used for nodes that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns
Allows set-like operations over the nodes as well as node attribute dict lookup and calling to
get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A
NodeView iterates over n and includes set operations.
When called, if data is False, an iterator over nodes. Otherwise an iterator of 2-tuples (node,
attribute value) where the attribute is specified in data. If data is True then the attribute becomes
the entire data dictionary.
Return type NodeView

2.2. Basic graph types 115


NetworkX Reference, Release 2.5

Notes

If your node data is not needed, it is simpler and equivalent to use the expression for n in G, or list(G).

Examples

There are two simple ways of getting a list of all nodes in the graph:

>>> G = nx.path_graph(3)
>>> list([Link])
[0, 1, 2]
>>> list(G)
[0, 1, 2]

To get the node data along with the nodes:

>>> G.add_node(1, time="5pm")


>>> [Link][0]["foo"] = "bar"
>>> list([Link](data=True))
[(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
>>> list([Link]())
[(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]

>>> list([Link](data="foo"))
[(0, 'bar'), (1, None), (2, None)]
>>> list([Link]("foo"))
[(0, 'bar'), (1, None), (2, None)]

>>> list([Link](data="time"))
[(0, None), (1, '5pm'), (2, None)]
>>> list([Link]("time"))
[(0, None), (1, '5pm'), (2, None)]

>>> list([Link](data="time", default="Not Available"))


[(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
>>> list([Link]("time", default="Not Available"))
[(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]

If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create
a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never
None:

>>> G = [Link]()
>>> G.add_node(0)
>>> G.add_node(1, weight=2)
>>> G.add_node(2, weight=3)
>>> dict([Link](data="weight", default=1))
{0: 1, 1: 2, 2: 3}

116 Chapter 2. Graph types


NetworkX Reference, Release 2.5

[Link].__iter__

MultiDiGraph.__iter__()
Iterate over the nodes. Use: ‘for n in G’.
Returns niter – An iterator over all nodes in the graph.
Return type iterator

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [n for n in G]
[0, 1, 2, 3]
>>> list(G)
[0, 1, 2, 3]

[Link].has_node

MultiDiGraph.has_node(n)
Returns True if the graph contains the node n.
Identical to n in G
Parameters n (node)

Examples

>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.has_node(0)
True

It is more readable and simpler to use

>>> 0 in G
True

[Link].__contains__

MultiDiGraph.__contains__(n)
Returns True if n is a node, False otherwise. Use: ‘n in G’.

2.2. Basic graph types 117


NetworkX Reference, Release 2.5

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> 1 in G
True

[Link]

property [Link]
An OutMultiEdgeView of the Graph as [Link] or [Link]().
edges(self, nbunch=None, data=False, keys=False, default=None)
The OutMultiEdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When
called, it also provides an EdgeDataView object which allows control of access to edge attributes (but does not
provide set-like operations). Hence, [Link][u, v]['color'] provides the value of the color attribute
for edge (u, v) while for (u, v, c) in [Link](data='color', default='red'): iter-
ates through all the edges yielding the color attribute with default 'red' if no color attribute exists.
Edges are returned as tuples with optional data and keys in the order (node, neighbor, key, data).
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• keys (bool, optional (default=False)) – If True, return edge keys with each edge.
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns edges – A view of edge attributes, usually it iterates over (u, v) (u, v, k) or (u, v, k, d) tuples
of edges, but can also be used for attribute lookup as edges[u, v, k]['foo'].
Return type EdgeView

Notes

Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.

Examples

>>> G = [Link]()
>>> nx.add_path(G, [0, 1, 2])
>>> key = G.add_edge(2, 3, weight=5)
>>> [e for e in [Link]()]
[(0, 1), (1, 2), (2, 3)]
>>> list([Link](data=True)) # default data is {} (empty dict)
[(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})]
>>> list([Link](data="weight", default=1))
[(0, 1, 1), (1, 2, 1), (2, 3, 5)]
>>> list([Link](keys=True)) # default keys are integers
(continues on next page)

118 Chapter 2. Graph types


NetworkX Reference, Release 2.5

(continued from previous page)


[(0, 1, 0), (1, 2, 0), (2, 3, 0)]
>>> list([Link](data=True, keys=True))
[(0, 1, 0, {}), (1, 2, 0, {}), (2, 3, 0, {'weight': 5})]
>>> list([Link](data="weight", default=1, keys=True))
[(0, 1, 0, 1), (1, 2, 0, 1), (2, 3, 0, 5)]
>>> list([Link]([0, 2]))
[(0, 1), (2, 3)]
>>> list([Link](0))
[(0, 1)]

See also:
in_edges, out_edges

[Link].out_edges

property MultiDiGraph.out_edges
An OutMultiEdgeView of the Graph as [Link] or [Link]().
edges(self, nbunch=None, data=False, keys=False, default=None)
The OutMultiEdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When
called, it also provides an EdgeDataView object which allows control of access to edge attributes (but does not
provide set-like operations). Hence, [Link][u, v]['color'] provides the value of the color attribute
for edge (u, v) while for (u, v, c) in [Link](data='color', default='red'): iter-
ates through all the edges yielding the color attribute with default 'red' if no color attribute exists.
Edges are returned as tuples with optional data and keys in the order (node, neighbor, key, data).
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• keys (bool, optional (default=False)) – If True, return edge keys with each edge.
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns edges – A view of edge attributes, usually it iterates over (u, v) (u, v, k) or (u, v, k, d) tuples
of edges, but can also be used for attribute lookup as edges[u, v, k]['foo'].
Return type EdgeView

2.2. Basic graph types 119


NetworkX Reference, Release 2.5

Notes

Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.

Examples

>>> G = [Link]()
>>> nx.add_path(G, [0, 1, 2])
>>> key = G.add_edge(2, 3, weight=5)
>>> [e for e in [Link]()]
[(0, 1), (1, 2), (2, 3)]
>>> list([Link](data=True)) # default data is {} (empty dict)
[(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})]
>>> list([Link](data="weight", default=1))
[(0, 1, 1), (1, 2, 1), (2, 3, 5)]
>>> list([Link](keys=True)) # default keys are integers
[(0, 1, 0), (1, 2, 0), (2, 3, 0)]
>>> list([Link](data=True, keys=True))
[(0, 1, 0, {}), (1, 2, 0, {}), (2, 3, 0, {'weight': 5})]
>>> list([Link](data="weight", default=1, keys=True))
[(0, 1, 0, 1), (1, 2, 0, 1), (2, 3, 0, 5)]
>>> list([Link]([0, 2]))
[(0, 1), (2, 3)]
>>> list([Link](0))
[(0, 1)]

See also:
in_edges, out_edges

[Link].in_edges

property MultiDiGraph.in_edges
An InMultiEdgeView of the Graph as G.in_edges or G.in_edges().
in_edges(self, nbunch=None, data=False, keys=False, default=None)
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• keys (bool, optional (default=False)) – If True, return edge keys with each edge.
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns in_edges – A view of edge attributes, usually it iterates over (u, v) or (u, v, k) or (u, v, k, d)
tuples of edges, but can also be used for attribute lookup as edges[u, v, k]['foo'].
Return type InMultiEdgeView
See also:
edges

120 Chapter 2. Graph types


NetworkX Reference, Release 2.5

[Link].has_edge

MultiDiGraph.has_edge(u, v, key=None)
Returns True if the graph has an edge between nodes u and v.
This is the same as v in G[u] or key in G[u][v] without KeyError exceptions.
Parameters
• u, v (nodes) – Nodes can be, for example, strings or numbers.
• key (hashable identifier, optional (default=None)) – If specified return True only if the edge
with key is found.
Returns edge_ind – True if edge is in the graph, False otherwise.
Return type bool

Examples

Can be called either using two nodes u, v, an edge tuple (u, v), or an edge tuple (u, v, key).

>>> G = [Link]() # or MultiDiGraph


>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.has_edge(0, 1) # using two nodes
True
>>> e = (0, 1)
>>> G.has_edge(*e) # e is a 2-tuple (u, v)
True
>>> G.add_edge(0, 1, key="a")
'a'
>>> G.has_edge(0, 1, key="a") # specify key
True
>>> e = (0, 1, "a")
>>> G.has_edge(*e) # e is a 3-tuple (u, v, 'a')
True

The following syntax are equivalent:

>>> G.has_edge(0, 1)
True
>>> 1 in G[0] # though this gives :exc:`KeyError` if 0 not in G
True

[Link].get_edge_data

MultiDiGraph.get_edge_data(u, v, key=None, default=None)


Returns the attribute dictionary associated with edge (u, v).
This is identical to G[u][v][key] except the default is returned instead of an exception is the edge doesn’t
exist.
Parameters
• u, v (nodes)
• default (any Python object (default=None)) – Value to return if the edge (u, v) is not found.

2.2. Basic graph types 121


NetworkX Reference, Release 2.5

• key (hashable identifier, optional (default=None)) – Return data only for the edge with
specified key.
Returns edge_dict – The edge attribute dictionary.
Return type dictionary

Examples

>>> G = [Link]() # or MultiDiGraph


>>> key = G.add_edge(0, 1, key="a", weight=7)
>>> G[0][1]["a"] # key='a'
{'weight': 7}
>>> [Link][0, 1, "a"] # key='a'
{'weight': 7}

Warning: we protect the graph data structure by making [Link] and G[1][2] read-only dict-like structures.
However, you can assign values to attributes in e.g. [Link][1, 2, 'a'] or G[1][2]['a'] using an
additional bracket as shown next. You need to specify all edge info to assign to the edge data associated with an
edge.

>>> G[0][1]["a"]["weight"] = 10
>>> [Link][0, 1, "a"]["weight"] = 10
>>> G[0][1]["a"]["weight"]
10
>>> [Link][1, 0, "a"]["weight"]
10

>>> G = [Link]() # or MultiDiGraph


>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.get_edge_data(0, 1)
{0: {}}
>>> e = (0, 1)
>>> G.get_edge_data(*e) # tuple form
{0: {}}
>>> G.get_edge_data("a", "b", default=0) # edge not in graph, return 0
0

[Link]

[Link](n)
Returns an iterator over successor nodes of n.
A successor of n is a node m such that there exists a directed edge from n to m.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
predecessors()

122 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Notes

neighbors() and successors() are the same.

[Link]

property [Link]
Graph adjacency object holding the neighbors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed
by neighbor to the edgekey-dict. So [Link][3][2][0]['color'] = 'blue' sets the color of the edge
(3, 2, 0) to "blue".
Iterating over [Link] behaves like a dict. Useful idioms include for nbr, datadict in [Link][n].
items():.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in
G[node].data('foo', default=1): works.
For directed graphs, [Link] holds outgoing (successor) info.

[Link].__getitem__

MultiDiGraph.__getitem__(n)
Returns a dict of neighbors of node n. Use: ‘G[n]’.
Parameters n (node) – A node in the graph.
Returns adj_dict – The adjacency dictionary for nodes connected to n.
Return type dictionary

Notes

G[n] is the same as [Link][n] and similar to [Link](n) (which is an iterator over [Link][n])

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G[0]
AtlasView({1: {}})

[Link]

[Link](n)
Returns an iterator over successor nodes of n.
A successor of n is a node m such that there exists a directed edge from n to m.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.

2.2. Basic graph types 123


NetworkX Reference, Release 2.5

See also:
predecessors()

Notes

neighbors() and successors() are the same.

[Link]

property [Link]
Graph adjacency object holding the successors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed
by neighbor to the edgekey-dict. So [Link][3][2][0]['color'] = 'blue' sets the color of the edge
(3, 2, 0) to "blue".
Iterating over [Link] behaves like a dict. Useful idioms include for nbr, datadict in [Link][n].
items():.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in
G[node].data('foo', default=1): works.
For directed graphs, [Link] is identical to [Link].

[Link]

[Link](n)
Returns an iterator over predecessor nodes of n.
A predecessor of n is a node m such that there exists a directed edge from m to n.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
successors()

[Link]

[Link]()
Returns an iterator over (node, adjacency dict) tuples for all nodes.
For directed graphs, only outgoing neighbors/adjacencies are included.
Returns adj_iter – An iterator over (node, adjacency dictionary) for all nodes in the graph.
Return type iterator

124 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [(n, nbrdict) for n, nbrdict in [Link]()]
[(0, {1: {}}), (1, {0: {}, 2: {}}), (2, {1: {}, 3: {}}), (3, {2: {}})]

[Link].nbunch_iter

MultiDiGraph.nbunch_iter(nbunch=None)
Returns an iterator over nodes contained in nbunch that are also in the graph.
The nodes in nbunch are checked for membership in the graph and if not are silently ignored.
Parameters nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
Returns niter – An iterator over nodes in nbunch that are also in the graph. If nbunch is None,
iterate over all nodes in the graph.
Return type iterator
Raises NetworkXError – If nbunch is not a node or or sequence of nodes. If a node in nbunch is
not hashable.
See also:
Graph.__iter__()

Notes

When nbunch is an iterator, the returned iterator yields values directly from nbunch, becoming exhausted when
nbunch is exhausted.
To test whether nbunch is a single node, one can use “if nbunch in self:”, even after processing with this routine.
If nbunch is not a node or a (possibly empty) sequence/iterator or None, a NetworkXError is raised. Also, if
any object in nbunch is not hashable, a NetworkXError is raised.

Counting nodes edges and neighbors

[Link]() Returns the number of nodes in the graph.


MultiDiGraph.number_of_nodes() Returns the number of nodes in the graph.
MultiDiGraph.__len__() Returns the number of nodes in the graph.
[Link] A DegreeView for the Graph as [Link] or [Link]().
MultiDiGraph.in_degree A DegreeView for (node, in_degree) or in_degree for
single node.
MultiDiGraph.out_degree Returns an iterator for (node, out-degree) or out-degree
for single node.
[Link]([weight]) Returns the number of edges or total of all edge weights.
MultiDiGraph.number_of_edges([u, v]) Returns the number of edges between two nodes.

2.2. Basic graph types 125


NetworkX Reference, Release 2.5

[Link]

[Link]()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
number_of_nodes(), __len__()

Examples

>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [Link]()
3

[Link].number_of_nodes

MultiDiGraph.number_of_nodes()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
order(), __len__()

Examples

>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.number_of_nodes()
3

[Link].__len__

MultiDiGraph.__len__()
Returns the number of nodes in the graph. Use: ‘len(G)’.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
number_of_nodes(), order()

126 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> len(G)
4

[Link]

property [Link]
A DegreeView for the Graph as [Link] or [Link]().
The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge
weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The name of an edge attribute that holds
the numerical value used as a weight. If None, then each edge has weight 1. The degree is
the sum of the edge weights adjacent to the node.
Returns
• If a single nodes is requested
• deg (int) – Degree of the node
• OR if multiple nodes are requested
• nd_iter (iterator) – The iterator returns two-tuples of (node, degree).
See also:
out_degree, in_degree

Examples

>>> G = [Link]()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> [Link](0) # node 0 with degree 1
1
>>> list([Link]([0, 1, 2]))
[(0, 1), (1, 2), (2, 2)]

2.2. Basic graph types 127


NetworkX Reference, Release 2.5

[Link].in_degree

property MultiDiGraph.in_degree
A DegreeView for (node, in_degree) or in_degree for single node.
The node in-degree is the number of edges pointing in to the node. The weighted node degree is the sum of the
edge weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical value used as a weight. If None, then each edge has weight 1. The degree is the sum of
the edge weights adjacent to the node.
Returns
• If a single node is requested
• deg (int) – Degree of the node
• OR if multiple nodes are requested
• nd_iter (iterator) – The iterator returns two-tuples of (node, in-degree).
See also:
degree, out_degree

Examples

>>> G = [Link]()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.in_degree(0) # node 0 with degree 0
0
>>> list(G.in_degree([0, 1, 2]))
[(0, 0), (1, 1), (2, 1)]

[Link].out_degree

property MultiDiGraph.out_degree
Returns an iterator for (node, out-degree) or out-degree for single node.
out_degree(self, nbunch=None, weight=None)
The node out-degree is the number of edges pointing out of the node. This function returns the out-degree for a
single node or an iterator for a bunch of nodes or if nothing is passed as argument.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical value used as a weight. If None, then each edge has weight 1. The degree is the sum of
the edge weights.

128 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Returns
• If a single node is requested
• deg (int) – Degree of the node
• OR if multiple nodes are requested
• nd_iter (iterator) – The iterator returns two-tuples of (node, out-degree).
See also:
degree, in_degree

Examples

>>> G = [Link]()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.out_degree(0) # node 0 with degree 1
1
>>> list(G.out_degree([0, 1, 2]))
[(0, 1), (1, 1), (2, 1)]

[Link]

[Link](weight=None)
Returns the number of edges or total of all edge weights.
Parameters weight (string or None, optional (default=None)) – The edge attribute that holds the
numerical value used as a weight. If None, then each edge has weight 1.
Returns
size – The number of edges or (if weight keyword is provided) the total weight sum.
If weight is None, returns an int. Otherwise a float (or more general numeric if the weights are
more general).
Return type numeric
See also:
number_of_edges()

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> [Link]()
3

>>> G = [Link]() # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> G.add_edge("a", "b", weight=2)
>>> G.add_edge("b", "c", weight=4)
>>> [Link]()
2
>>> [Link](weight="weight")
6.0

2.2. Basic graph types 129


NetworkX Reference, Release 2.5

[Link].number_of_edges

MultiDiGraph.number_of_edges(u=None, v=None)
Returns the number of edges between two nodes.
Parameters u, v (nodes, optional (Gefault=all edges)) – If u and v are specified, return the number
of edges between u and v. Otherwise return the total number of all edges.
Returns nedges – The number of edges in the graph. If nodes u and v are specified return the
number of edges between those nodes. If the graph is directed, this only returns the number of
edges from u to v.
Return type int
See also:
size()

Examples

For undirected multigraphs, this method counts the total number of edges in the graph:

>>> G = [Link]()
>>> G.add_edges_from([(0, 1), (0, 1), (1, 2)])
[0, 1, 0]
>>> G.number_of_edges()
3

If you specify two nodes, this counts the total number of edges joining the two nodes:

>>> G.number_of_edges(0, 1)
2

For directed multigraphs, this method can count the total number of directed edges from u to v:

>>> G = [Link]()
>>> G.add_edges_from([(0, 1), (0, 1), (1, 0)])
[0, 1, 0]
>>> G.number_of_edges(0, 1)
2
>>> G.number_of_edges(1, 0)
1

Making copies and subgraphs

[Link]([as_view]) Returns a copy of the graph.


MultiDiGraph.to_undirected([reciprocal, Returns an undirected representation of the digraph.
as_view])
MultiDiGraph.to_directed([as_view]) Returns a directed representation of the graph.
[Link](nodes) Returns a SubGraph view of the subgraph induced on
nodes.
MultiDiGraph.edge_subgraph(edges) Returns the subgraph induced by the specified edges.
[Link]([copy]) Returns the reverse of the graph.

130 Chapter 2. Graph types


NetworkX Reference, Release 2.5

[Link]

[Link](as_view=False)
Returns a copy of the graph.
The copy method by default returns an independent shallow copy of the graph and attributes. That is, if an
attribute is a container, that container is shared by the original an the copy. Use Python’s [Link] for
new containers.
If as_view is True then a view is returned instead of a copy.

Notes

All copies reproduce the graph structure, but data attributes may be handled in different ways. There are four
types of copies of a graph that people might want.
Deepcopy – A “deepcopy” copies the graph structure as well as all data attributes and any objects they might
contain. The entire graph object is new so that changes in the copy do not affect the original object. (see Python’s
[Link])
Data Reference (Shallow) – For a shallow copy the graph structure is copied but the edge, node and graph at-
tribute dicts are references to those in the original graph. This saves time and memory but could cause confusion
if you change an attribute in one graph and it changes the attribute in the other. NetworkX does not provide this
level of shallow copy.
Independent Shallow – This copy creates new independent attribute dicts and then does a shallow copy of the
attributes. That is, any attributes that are containers are shared between the new graph and the original. This is
exactly what [Link]() provides. You can obtain this style copy using:

>>> G = nx.path_graph(5)
>>> H = [Link]()
>>> H = [Link](as_view=False)
>>> H = [Link](G)
>>> H = G.__class__(G)

Fresh Data – For fresh data, the graph structure is copied while new empty data attribute dicts are created. The
resulting graph is independent of the original and it has no edge, node or graph attributes. Fresh copies are not
enabled. Instead use:

>>> H = G.__class__()
>>> H.add_nodes_from(G)
>>> H.add_edges_from([Link])

View – Inspired by dict-views, graph-views act like read-only versions of the original graph, providing a copy
of the original structure without requiring any memory for copying the information.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Parameters as_view (bool, optional (default=False)) – If True, the returned graph-view provides a
read-only view of the original graph without actually copying any data.
Returns G – A copy of the graph.
Return type Graph
See also:

to_directed() return a directed copy of the graph.

2.2. Basic graph types 131


NetworkX Reference, Release 2.5

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> H = [Link]()

[Link].to_undirected

MultiDiGraph.to_undirected(reciprocal=False, as_view=False)
Returns an undirected representation of the digraph.
Parameters
• reciprocal (bool (optional)) – If True only keep edges that appear in both directions in the
original digraph.
• as_view (bool (optional, default=False)) – If True return an undirected view of the original
directed graph.
Returns G – An undirected graph with the same name and nodes and with edge (u, v, data) if either
(u, v, data) or (v, u, data) is in the digraph. If both edges exist in digraph and their edge data is
different, only one edge is created with an arbitrary choice of which edge data to use. You must
check and correct for this manually if desired.
Return type MultiGraph
See also:
MultiGraph(), copy(), add_edge(), add_edges_from()

Notes

This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar D=MultiiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Warning: If you have subclassed MultiDiGraph to use dict-like objects in the data structure, those changes do
not transfer to the MultiGraph created by this method.

Examples

>>> G = nx.path_graph(2) # or MultiGraph, etc


>>> H = G.to_directed()
>>> list([Link])
[(0, 1), (1, 0)]
>>> G2 = H.to_undirected()
>>> list([Link])
[(0, 1)]

132 Chapter 2. Graph types


NetworkX Reference, Release 2.5

[Link].to_directed

MultiDiGraph.to_directed(as_view=False)
Returns a directed representation of the graph.
Returns G – A directed graph with the same name, same nodes, and with each edge (u, v, data)
replaced by two directed edges (u, v, data) and (v, u, data).
Return type MultiDiGraph

Notes

This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar D=DiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Warning: If you have subclassed MultiGraph to use dict-like objects in the data structure, those changes do not
transfer to the MultiDiGraph created by this method.

Examples

>>> G = [Link]() # or MultiGraph, etc


>>> G.add_edge(0, 1)
>>> H = G.to_directed()
>>> list([Link])
[(0, 1), (1, 0)]

If already directed, return a (deep) copy

>>> G = [Link]() # or MultiDiGraph, etc


>>> G.add_edge(0, 1)
>>> H = G.to_directed()
>>> list([Link])
[(0, 1)]

[Link]

[Link](nodes)
Returns a SubGraph view of the subgraph induced on nodes.
The induced subgraph of the graph contains the nodes in nodes and the edges between those nodes.
Parameters nodes (list, iterable) – A container of nodes which will be iterated through once.
Returns G – A subgraph view of the graph. The graph structure cannot be changed but node/edge
attributes can and are shared with the original graph.
Return type SubGraph View

2.2. Basic graph types 133


NetworkX Reference, Release 2.5

Notes

The graph, edge and node attributes are shared with the original graph. Changes to the graph structure is ruled
out by the view, but changes to attributes are reflected in the original graph.
To create a subgraph with its own copy of the edge/node attributes use: [Link](nodes).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(nodes)])
Subgraph views are sometimes NOT what you want. In most cases where you want to do more than simply look
at the induced edges, it makes more sense to just create the subgraph as its own graph with code like:

# Create a subgraph SG based on a (possibly multigraph) G


SG = G.__class__()
SG.add_nodes_from((n, [Link][n]) for n in largest_wcc)
if SG.is_multigraph():
SG.add_edges_from((n, nbr, key, d)
for n, nbrs in [Link]() if n in largest_wcc
for nbr, keydict in [Link]() if nbr in largest_wcc
for key, d in [Link]())
else:
SG.add_edges_from((n, nbr, d)
for n, nbrs in [Link]() if n in largest_wcc
for nbr, d in [Link]() if nbr in largest_wcc)
[Link]([Link])

Examples

>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc


>>> H = [Link]([0, 1, 2])
>>> list([Link])
[(0, 1), (1, 2)]

[Link].edge_subgraph

MultiDiGraph.edge_subgraph(edges)
Returns the subgraph induced by the specified edges.
The induced subgraph contains each edge in edges and each node incident to any one of those edges.
Parameters edges (iterable) – An iterable of edges in this graph.
Returns G – An edge-induced subgraph of this graph with the same edge attributes.
Return type Graph

134 Chapter 2. Graph types


NetworkX Reference, Release 2.5

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()

Examples

>>> G = nx.path_graph(5)
>>> H = G.edge_subgraph([(0, 1), (3, 4)])
>>> list([Link])
[0, 1, 3, 4]
>>> list([Link])
[(0, 1), (3, 4)]

[Link]

[Link](copy=True)
Returns the reverse of the graph.
The reverse is a graph with the same nodes and edges but with the directions of the edges reversed.
Parameters copy (bool optional (default=True)) – If True, return a new DiGraph holding the re-
versed edges. If False, the reverse graph is created using a view of the original graph.

2.2.5 Ordered Graphs—Consistently ordered graphs

Consistently ordered variants of the default base classes. Note that if you are using Python 3.6+, you shouldn’t need
these classes because the dicts in Python 3.6+ are ordered. Note also that there are many differing expectations for the
word “ordered” and that these classes may not provide the order you expect. The intent here is to give a consistent
order not a particular order.
The Ordered (Di/Multi/MultiDi) Graphs give a consistent order for reporting of nodes and edges. The order of node
reporting agrees with node adding, but for edges, the order is not necessarily the order that the edges were added.
In general, you should use the default (i.e., unordered) graph classes. However, there are times (e.g., when testing)
when you may need the order preserved.
Special care is required when using subgraphs of the Ordered classes. The order of nodes in the subclass is not
necessarily the same order as the original class. In general it is probably better to avoid using subgraphs and replace
with code similar to:

# instead of SG = [Link](ordered_nodes)
SG = [Link]()
SG.add_nodes_from(ordered_nodes)
SG.add_edges_from((u, v) for (u, v) in [Link]() if u in SG if v in SG)

class OrderedGraph(incoming_graph_data=None, **attr)


Consistently ordered variant of Graph.
class OrderedDiGraph(incoming_graph_data=None, **attr)
Consistently ordered variant of DiGraph.

2.2. Basic graph types 135


NetworkX Reference, Release 2.5

class OrderedMultiGraph(incoming_graph_data=None, **attr)


Consistently ordered variant of MultiGraph.
class OrderedMultiDiGraph(incoming_graph_data=None, **attr)
Consistently ordered variant of MultiDiGraph.

Note: NetworkX uses dicts to store the nodes and neighbors in a graph. So the reporting of nodes and edges for
the base graph classes will not necessarily be consistent across versions and platforms. If you need the order of nodes
and edges to be consistent (e.g., when writing automated tests), please see OrderedGraph, OrderedDiGraph,
OrderedMultiGraph, or OrderedMultiDiGraph, which behave like the base graph classes but give a consis-
tent order for reporting of nodes and edges.

2.3 Graph Views

View of Graphs as SubGraph, Reverse, Directed, Undirected.


In some algorithms it is convenient to temporarily morph a graph to exclude some nodes or edges. It should be better
to do that via a view than to remove and then re-add. In other algorithms it is convenient to temporarily morph a graph
to reverse directed edges, or treat a directed graph as undirected, etc. This module provides those graph views.
The resulting views are essentially read-only graphs that report data from the orignal graph object. We provide an
attribute G._graph which points to the underlying graph object.
Note: Since graphviews look like graphs, one can end up with view-of-view-of-view chains. Be careful with chains
because they become very slow with about 15 nested views. For the common simple case of node induced subgraphs
created from the graph class, we short-cut the chain by returning a subgraph of the original graph directly rather than
a subgraph of a subgraph. We are careful not to disrupt any edge filter in the middle subgraph. In general, determining
how to short-cut the chain is tricky and much harder with restricted_views than with induced subgraphs. Often it is
easiest to use .copy() to avoid chains.

generic_graph_view(G[, create_using])
subgraph_view(G[, filter_node, filter_edge]) View of G applying a filter on nodes and edges.
reverse_view(G) View of G with edge directions reversed

2.3.1 [Link].generic_graph_view

generic_graph_view(G, create_using=None)

2.3.2 [Link].subgraph_view

subgraph_view(G, filter_node=<function no_filter>, filter_edge=<function no_filter>)


View of G applying a filter on nodes and edges.
subgraph_view provides a read-only view of the input graph that excludes nodes and edges based on the
outcome of two filter functions filter_node and filter_edge.
The filter_node function takes one argument — the node — and returns True if the node should be
included in the subgraph, and False if it should not be included.
The filter_edge function takes two (or three arguments if G is a multi-graph) — the nodes describing an
edge, plus the edge-key if parallel edges are possible — and returns True if the edge should be included in the
subgraph, and False if it should not be included.

136 Chapter 2. Graph types


NetworkX Reference, Release 2.5

Both node and edge filter functions are called on graph elements as they are queried, meaning there is no up-front
cost to creating the view.
Parameters
• G ([Link]) – A directed/undirected graph/multigraph
• filter_node (callable, optional) – A function taking a node as input, which returns True if
the node should appear in the view.
• filter_edge (callable, optional) – A function taking as input the two nodes describing an
edge (plus the edge-key if G is a multi-graph), which returns True if the edge should appear
in the view.
Returns graph – A read-only graph view of the input graph.
Return type [Link]

Examples

>>> G = nx.path_graph(6)

Filter functions operate on the node, and return True if the node should appear in the view:

>>> def filter_node(n1):


... return n1 != 5
...
>>> view = nx.subgraph_view(G, filter_node=filter_node)
>>> [Link]()
NodeView((0, 1, 2, 3, 4))

We can use a closure pattern to filter graph elements based on additional data — for example, filtering on edge
data attached to the graph:

>>> G[3][4]["cross_me"] = False


>>> def filter_edge(n1, n2):
... return G[n1][n2].get("cross_me", True)
...
>>> view = nx.subgraph_view(G, filter_edge=filter_edge)
>>> [Link]()
EdgeView([(0, 1), (1, 2), (2, 3), (4, 5)])

>>> view = nx.subgraph_view(G, filter_node=filter_node, filter_edge=filter_edge,)


>>> [Link]()
NodeView((0, 1, 2, 3, 4))
>>> [Link]()
EdgeView([(0, 1), (1, 2), (2, 3)])

2.3. Graph Views 137


NetworkX Reference, Release 2.5

2.3.3 [Link].reverse_view

reverse_view(G)
View of G with edge directions reversed
reverse_view returns a read-only view of the input graph where edge directions are reversed.
Identical to [Link](copy=False)
Parameters G ([Link])
Returns graph
Return type [Link]

Examples

>>> G = [Link]()
>>> G.add_edge(1, 2)
>>> G.add_edge(2, 3)
>>> [Link]()
OutEdgeView([(1, 2), (2, 3)])

>>> view = nx.reverse_view(G)


>>> [Link]()
OutEdgeView([(2, 1), (3, 2)])

2.4 Filters

Note: Filters can be used with views to restrict the view (or expand it). They can filter nodes or filter edges. These
examples are intended to help you build new ones. They may instead contain all the filters you ever need.

Filter factories to hide or show sets of nodes and edges.


These filters return the function used when creating SubGraph.

no_filter(*items)
hide_nodes(nodes)
hide_edges(edges)
hide_diedges(edges)
hide_multidiedges(edges)
hide_multiedges(edges)
show_nodes(nodes)
show_edges(edges)
show_diedges(edges)
show_multidiedges(edges)
show_multiedges(edges)

138 Chapter 2. Graph types


NetworkX Reference, Release 2.5

2.4.1 [Link].no_filter

no_filter(*items)

2.4.2 [Link].hide_nodes

hide_nodes(nodes)

2.4.3 [Link].hide_edges

hide_edges(edges)

2.4.4 [Link].hide_diedges

hide_diedges(edges)

2.4.5 [Link].hide_multidiedges

hide_multidiedges(edges)

2.4.6 [Link].hide_multiedges

hide_multiedges(edges)

2.4.7 [Link].show_nodes

class show_nodes(nodes)

__init__(nodes)
Initialize self. See help(type(self)) for accurate signature.

Methods

__init__(nodes) Initialize self.

2.4. Filters 139


NetworkX Reference, Release 2.5

2.4.8 [Link].show_edges

show_edges(edges)

2.4.9 [Link].show_diedges

show_diedges(edges)

2.4.10 [Link].show_multidiedges

show_multidiedges(edges)

2.4.11 [Link].show_multiedges

show_multiedges(edges)

140 Chapter 2. Graph types


CHAPTER

THREE

ALGORITHMS

3.1 Approximations and Heuristics

Approximations of graph properties and Heuristic functions for optimization problems.

Warning: The approximation submodule is not imported in the top-level networkx.

These functions can be imported with from [Link] import


approximation.

3.1.1 Connectivity

Fast approximation for node connectivity

all_pairs_node_connectivity(G[, nbunch, Compute node connectivity between all pairs of nodes.


cutoff])
local_node_connectivity(G, source, target[, Compute node connectivity between source and target.
. . . ])
node_connectivity(G[, s, t]) Returns an approximation for node connectivity for a
graph or digraph G.

[Link].all_pairs_node_connectivity

all_pairs_node_connectivity(G, nbunch=None, cutoff=None)


Compute node connectivity between all pairs of nodes.
Pairwise or local node connectivity between two distinct and nonadjacent nodes is the minimum number of
nodes that must be removed (minimum separating cutset) to disconnect them. By Menger’s theorem, this is
equal to the number of node independent paths (paths that share no nodes other than source and target). Which
is what we compute in this function.
This algorithm is a fast approximation that gives an strict lower bound on the actual number of node independent
paths between two nodes1 . It works for both directed and undirected graphs.
Parameters
• G (NetworkX graph)
1 White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
[Link]

141
NetworkX Reference, Release 2.5

• nbunch (container) – Container of nodes. If provided node connectivity will be computed


only over pairs of nodes in nbunch.
• cutoff (integer) – Maximum node connectivity to consider. If None, the minimum degree
of source or target is used as a cutoff in each pair of nodes. Default value None.
Returns K – Dictionary, keyed by source and target, of pairwise node connectivity
Return type dictionary
See also:
local_node_connectivity(), node_connectivity()

References

[Link].local_node_connectivity

local_node_connectivity(G, source, target, cutoff=None)


Compute node connectivity between source and target.
Pairwise or local node connectivity between two distinct and nonadjacent nodes is the minimum number of
nodes that must be removed (minimum separating cutset) to disconnect them. By Menger’s theorem, this is
equal to the number of node independent paths (paths that share no nodes other than source and target). Which
is what we compute in this function.
This algorithm is a fast approximation that gives an strict lower bound on the actual number of node independent
paths between two nodes1 . It works for both directed and undirected graphs.
Parameters
• G (NetworkX graph)
• source (node) – Starting node for node connectivity
• target (node) – Ending node for node connectivity
• cutoff (integer) – Maximum node connectivity to consider. If None, the minimum degree
of source or target is used as a cutoff. Default value None.
Returns k – pairwise node connectivity
Return type integer

Examples

>>> # Platonic octahedral graph has node connectivity 4


>>> # for each non adjacent node pair
>>> from [Link] import approximation as approx
>>> G = nx.octahedral_graph()
>>> approx.local_node_connectivity(G, 0, 5)
4

1 White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035

[Link]

142 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Notes

This algorithm1 finds node independents paths between two nodes by computing their shortest path using BFS,
marking the nodes of the path found as ‘used’ and then searching other shortest paths excluding the nodes
marked as used until no more paths exist. It is not exact because a shortest path could use nodes that, if the path
were longer, may belong to two different node independent paths. Thus it only guarantees an strict lower bound
on node connectivity.
Note that the authors propose a further refinement, losing accuracy and gaining speed, which is not implemented
yet.
See also:
all_pairs_node_connectivity(), node_connectivity()

References

[Link].node_connectivity

node_connectivity(G, s=None, t=None)


Returns an approximation for node connectivity for a graph or digraph G.
Node connectivity is equal to the minimum number of nodes that must be removed to disconnect G or render it
trivial. By Menger’s theorem, this is equal to the number of node independent paths (paths that share no nodes
other than source and target).
If source and target nodes are provided, this function returns the local node connectivity: the minimum number
of nodes that must be removed to break all paths from source to target in G.
This algorithm is based on a fast approximation that gives an strict lower bound on the actual number of node
independent paths between two nodes1 . It works for both directed and undirected graphs.
Parameters
• G (NetworkX graph) – Undirected graph
• s (node) – Source node. Optional. Default value: None.
• t (node) – Target node. Optional. Default value: None.
Returns K – Node connectivity of G, or local node connectivity if source and target are provided.
Return type integer

Examples

>>> # Platonic octahedral graph is 4-node-connected


>>> from [Link] import approximation as approx
>>> G = nx.octahedral_graph()
>>> approx.node_connectivity(G)
4

1 White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035

[Link]

3.1. Approximations and Heuristics 143


NetworkX Reference, Release 2.5

Notes

This algorithm1 finds node independents paths between two nodes by computing their shortest path using BFS,
marking the nodes of the path found as ‘used’ and then searching other shortest paths excluding the nodes
marked as used until no more paths exist. It is not exact because a shortest path could use nodes that, if the path
were longer, may belong to two different node independent paths. Thus it only guarantees an strict lower bound
on node connectivity.
See also:
all_pairs_node_connectivity(), local_node_connectivity()

References

3.1.2 K-components

Fast approximation for k-component structure

k_components(G[, min_density]) Returns the approximate k-component structure of a


graph G.

[Link].k_components

k_components(G, min_density=0.95)
Returns the approximate k-component structure of a graph G.
A k-component is a maximal subgraph of a graph G that has, at least, node connectivity k: we need to remove at
least k nodes to break it into more components. k-components have an inherent hierarchical structure because
they are nested in terms of connectivity: a connected graph can contain several 2-components, each of which
can contain one or more 3-components, and so forth.
This implementation is based on the fast heuristics to approximate the k-component structure of a graph1 .
Which, in turn, it is based on a fast approximation algorithm for finding good lower bounds of the number of
node independent paths between two nodes2 .
Parameters
• G (NetworkX graph) – Undirected graph
• min_density (Float) – Density relaxation threshold. Default value 0.95
Returns k_components – Dictionary with connectivity level k as key and a list of sets of nodes that
form a k-component of level k as values.
Return type dict
1 Torrents, J. and F. Ferraro (2015) Structural Cohesion: Visualization and Heuristics for Fast Computation. [Link]
2 White, Douglas R., and Mark Newman (2001) A Fast Algorithm for Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
[Link]

144 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Examples

>>> # Petersen graph has 10 nodes and it is triconnected, thus all


>>> # nodes are in a single component on all three connectivity levels
>>> from [Link] import approximation as apxa
>>> G = nx.petersen_graph()
>>> k_components = apxa.k_components(G)

Notes

The logic of the approximation algorithm for computing the k-component structure1 is based on repeatedly
applying simple and fast algorithms for k-cores and biconnected components in order to narrow down the
number of pairs of nodes over which we have to compute White and Newman’s approximation algorithm for
finding node independent paths2 . More formally, this algorithm is based on Whitney’s theorem, which states
an inclusion relation among node connectivity, edge connectivity, and minimum degree for any graph G. This
theorem implies that every k-component is nested inside a k-edge-component, which in turn, is contained in a
k-core. Thus, this algorithm computes node independent paths among pairs of nodes in each biconnected part
of each k-core, and repeats this procedure for each k from 3 to the maximal core number of a node in the input
graph.
Because, in practice, many nodes of the core of level k inside a bicomponent actually are part of a component
of level k, the auxiliary graph needed for the algorithm is likely to be very dense. Thus, we use a complement
graph data structure (see AntiGraph) to save memory. AntiGraph only stores information of the edges that
are not present in the actual auxiliary graph. When applying algorithms to this complement graph data structure,
it behaves as if it were the dense version.
See also:
k_components()

References

3.1.3 Clique

Functions for computing large cliques.

max_clique(G) Find the Maximum Clique


clique_removal(G) Repeatedly remove cliques from the graph.
large_clique_size(G) Find the size of a large clique in a graph.

[Link].max_clique

max_clique(G)
Find the Maximum Clique
Finds the 𝑂(|𝑉 |/(𝑙𝑜𝑔|𝑉 |)2 ) apx of maximum clique/independent set in the worst case.
Parameters G (NetworkX graph) – Undirected graph
Returns clique – The apx-maximum clique of the graph
Return type set

3.1. Approximations and Heuristics 145


NetworkX Reference, Release 2.5

Notes

A clique in an undirected graph G = (V, E) is a subset of the vertex set C subseteq V such that for every two
vertices in C there exists an edge connecting the two. This is equivalent to saying that the subgraph induced by
C is complete (in some cases, the term clique may also refer to the subgraph).
A maximum clique is a clique of the largest possible size in a given graph. The clique number omega(G) of
a graph G is the number of vertices in a maximum clique in G. The intersection number of G is the smallest
number of cliques that together cover all edges of G.
[Link]

References

[Link].clique_removal

clique_removal(G)
Repeatedly remove cliques from the graph.
Results in a 𝑂(|𝑉 |/(log |𝑉 |)2 ) approximation of maximum clique and independent set. Returns the largest
independent set found, along with found maximal cliques.
Parameters G (NetworkX graph) – Undirected graph
Returns max_ind_cliques – 2-tuple of Maximal Independent Set and list of maximal cliques (sets).
Return type (set, list) tuple

References

[Link].large_clique_size

large_clique_size(G)
Find the size of a large clique in a graph.
A clique is a subset of nodes in which each pair of nodes is adjacent. This function is a heuristic for finding the
size of a large clique in the graph.
Parameters G (NetworkX graph)
Returns The size of a large clique in the graph.
Return type int

Notes

This implementation is from1 . Its worst case time complexity is 𝑂(𝑛𝑑2 ), where n is the number of nodes in the
graph and d is the maximum degree.
This function is a heuristic, which means it may work well in practice, but there is no rigorous mathematical
guarantee on the ratio between the returned number and the actual largest clique size in the graph.
1
Pattabiraman, Bharath, et al. “Fast Algorithms for the Maximum Clique Problem on Massive Graphs with Applications to Overlapping
Community Detection.” Internet Mathematics 11.4-5 (2015): 421–448. <[Link]

146 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

References

See also:

[Link].max_clique() A function that returns an ap-


proximate maximum clique with a guarantee on the approximation ratio.
[Link] Functions for finding the exact maximum clique in a graph.

3.1.4 Clustering

average_clustering(G[, trials, seed]) Estimates the average clustering coefficient of G.

[Link].clustering_coefficient.average_clustering

average_clustering(G, trials=1000, seed=None)


Estimates the average clustering coefficient of G.
The local clustering of each node in G is the fraction of triangles that actually exist over all possible triangles in
its neighborhood. The average clustering coefficient of a graph G is the mean of local clusterings.
This function finds an approximate average clustering coefficient for G by repeating n times (defined in
trials) the following experiment: choose a node at random, choose two of its neighbors at random, and
check if they are connected. The approximate coefficient is the fraction of triangles found over the number of
trials1 .
Parameters
• G (NetworkX graph)
• trials (integer) – Number of trials to perform (default 1000).
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
Returns c – Approximated average clustering coefficient.
Return type float

References

3.1.5 Dominating Set

Functions for finding node and edge dominating sets.


A dominating set for an undirected graph G with vertex set V and edge set E is a subset D of V such that every vertex
not in D is adjacent to at least one member of D. An edge dominating set is a subset F of E such that every edge not
in F is incident to an endpoint of at least one edge in F.

min_weighted_dominating_set(G[, weight]) Returns a dominating set that approximates the mini-


mum weight node dominating set.
min_edge_dominating_set(G) Returns minimum cardinality edge dominating set.
1 Schank, Thomas, and Dorothea Wagner. Approximating clustering coefficient and transitivity. Universität Karlsruhe, Fakultät für Informatik,

2004. [Link]

3.1. Approximations and Heuristics 147


NetworkX Reference, Release 2.5

[Link].dominating_set.min_weighted_dominating_set

min_weighted_dominating_set(G, weight=None)
Returns a dominating set that approximates the minimum weight node dominating set.
Parameters
• G (NetworkX graph) – Undirected graph.
• weight (string) – The node attribute storing the weight of an node. If provided, the node
attribute with this key must be a number for each node. If not provided, each node is assumed
to have weight one.
Returns min_weight_dominating_set – A set of nodes, the sum of whose weights is no more than
(log w(V)) w(V^*), where w(V) denotes the sum of the weights of each node in the graph
and w(V^*) denotes the sum of the weights of each node in the minimum weight dominating
set.
Return type set

Notes

This algorithm computes an approximate minimum weighted dominating set for the graph G. The returned
solution has weight (log w(V)) w(V^*), where w(V) denotes the sum of the weights of each node in the
graph and w(V^*) denotes the sum of the weights of each node in the minimum weight dominating set for the
graph.
This implementation of the algorithm runs in 𝑂(𝑚) time, where 𝑚 is the number of edges in the graph.

References

[Link].dominating_set.min_edge_dominating_set

min_edge_dominating_set(G)
Returns minimum cardinality edge dominating set.
Parameters G (NetworkX graph) – Undirected graph
Returns min_edge_dominating_set – Returns a set of dominating edges whose size is no more
than 2 * OPT.
Return type set

Notes

The algorithm computes an approximate solution to the edge dominating set problem. The result is no more
than 2 * OPT in terms of size of the set. Runtime of the algorithm is 𝑂(|𝐸|).

148 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

3.1.6 Independent Set

Independent Set
Independent set or stable set is a set of vertices in a graph, no two of which are adjacent. That is, it is a set I of vertices
such that for every two vertices in I, there is no edge connecting the two. Equivalently, each edge in the graph has at
most one endpoint in I. The size of an independent set is the number of vertices it contains.
A maximum independent set is a largest independent set for a given graph G and its size is denoted 𝛼(𝐺). The problem
of finding such a set is called the maximum independent set problem and is an NP-hard optimization problem. As
such, it is unlikely that there exists an efficient algorithm for finding a maximum independent set of a graph.
Wikipedia: Independent set
Independent set algorithm is based on the following paper:
𝑂(|𝑉 |/(𝑙𝑜𝑔|𝑉 |)2 ) apx of maximum clique/independent set.
Boppana, R., & Halldórsson, M. M. (1992). Approximating maximum independent sets by excluding subgraphs. BIT
Numerical Mathematics, 32(2), 180–196. Springer. doi:10.1007/BF01994876

maximum_independent_set(G) Returns an approximate maximum independent set.

[Link].independent_set.maximum_independent_set

maximum_independent_set(G)
Returns an approximate maximum independent set.
Parameters G (NetworkX graph) – Undirected graph
Returns iset – The apx-maximum independent set
Return type Set

Notes

Finds the 𝑂(|𝑉 |/(𝑙𝑜𝑔|𝑉 |)2 ) apx of independent set in the worst case.

References

3.1.7 Matching

Graph Matching

Given a graph G = (V,E), a matching M in G is a set of pairwise non-adjacent edges; that is, no two edges share a
common vertex.
Wikipedia: Matching

min_maximal_matching(G) Returns the minimum maximal matching of G.

3.1. Approximations and Heuristics 149


NetworkX Reference, Release 2.5

[Link].min_maximal_matching

min_maximal_matching(G)
Returns the minimum maximal matching of G. That is, out of all maximal matchings of the graph G, the smallest
is returned.
Parameters G (NetworkX graph) – Undirected graph
Returns min_maximal_matching – Returns a set of edges such that no two edges share a common
endpoint and every edge not in the set shares some common endpoint in the set. Cardinality will
be 2*OPT in the worst case.
Return type set

Notes

The algorithm computes an approximate solution fo the minimum maximal cardinality matching problem. The
solution is no more than 2 * OPT in size. Runtime is 𝑂(|𝐸|).

References

3.1.8 Ramsey

Ramsey numbers.

ramsey_R2(G) Compute the largest clique and largest independent set


in G.

[Link].ramsey_R2

ramsey_R2(G)
Compute the largest clique and largest independent set in G.
This can be used to estimate bounds for the 2-color Ramsey number R(2;s,t) for G.
This is a recursive implementation which could run into trouble for large recursions. Note that self-loop edges
are ignored.
Parameters G (NetworkX graph) – Undirected graph
Returns max_pair – Maximum clique, Maximum independent set.
Return type (set, set) tuple

3.1.9 Steiner Tree

metric_closure(G[, weight]) Return the metric closure of a graph.


steiner_tree(G, terminal_nodes[, weight]) Return an approximation to the minimum Steiner tree of
a graph.

150 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

[Link].metric_closure

metric_closure(G, weight='weight')
Return the metric closure of a graph.
The metric closure of a graph G is the complete graph in which each edge is weighted by the shortest path
distance between the nodes in G .
Parameters G (NetworkX graph)
Returns Metric closure of the graph G.
Return type NetworkX graph

[Link].steiner_tree

steiner_tree(G, terminal_nodes, weight='weight')


Return an approximation to the minimum Steiner tree of a graph.
The minimum Steiner tree of G w.r.t a set of terminal_nodes is a tree within G that spans those nodes and
has minimum size (sum of edge weights) among all such trees.
The minimum Steiner tree can be approximated by computing the minimum spanning tree of the subgraph of
the metric closure of G induced by the terminal nodes, where the metric closure of G is the complete graph in
which each edge is weighted by the shortest path distance between the nodes in G . This algorithm produces a
tree whose weight is within a (2 - (2 / t)) factor of the weight of the optimal Steiner tree where t is number of
terminal nodes.
Parameters
• G (NetworkX graph)
• terminal_nodes (list) – A list of terminal nodes for which minimum steiner tree is to be
found.
Returns Approximation to the minimum steiner tree of G induced by terminal_nodes .
Return type NetworkX graph

Notes

For multigraphs, the edge between two nodes with minimum weight is the edge put into the Steiner tree.

References

3.1.10 Treewidth

Functions for computing treewidth decomposition.


Treewidth of an undirected graph is a number associated with the graph. It can be defined as the size of the largest
vertex set (bag) in a tree decomposition of the graph minus one.
Wikipedia: Treewidth

3.1. Approximations and Heuristics 151


NetworkX Reference, Release 2.5

The notions of treewidth and tree decomposition have gained their attractiveness partly because many graph and
network problems that are intractable (e.g., NP-hard) on arbitrary graphs become efficiently solvable (e.g., with a
linear time algorithm) when the treewidth of the input graphs is bounded by a constant12 .
There are two different functions for computing a tree decomposition: treewidth_min_degree() and
treewidth_min_fill_in().

treewidth_min_degree(G) Returns a treewidth decomposition using the Minimum


Degree heuristic.
treewidth_min_fill_in(G) Returns a treewidth decomposition using the Minimum
Fill-in heuristic.

[Link].treewidth_min_degree

treewidth_min_degree(G)
Returns a treewidth decomposition using the Minimum Degree heuristic.
The heuristic chooses the nodes according to their degree, i.e., first the node with the lowest degree is chosen,
then the graph is updated and the corresponding node is removed. Next, a new node with the lowest degree is
chosen, and so on.
Parameters G (NetworkX graph)
Returns Treewidth decomposition – 2-tuple with treewidth and the corresponding decomposed
tree.
Return type (int, Graph) tuple

[Link].treewidth_min_fill_in

treewidth_min_fill_in(G)
Returns a treewidth decomposition using the Minimum Fill-in heuristic.
The heuristic chooses a node from the graph, where the number of edges added turning the neighbourhood of
the chosen node into clique is as small as possible.
Parameters G (NetworkX graph)
Returns Treewidth decomposition – 2-tuple with treewidth and the corresponding decomposed
tree.
Return type (int, Graph) tuple
1 Hans L. Bodlaender and Arie M. C. A. Koster. 2010. “Treewidth computations [Link] bounds”. Inf. Comput. 208, 3 (March 2010),259-275.

[Link]
2 Hans L. Bodlaender. “Discovering Treewidth”. Institute of Information and Computing Sciences, Utrecht University. Technical Report

UU-CS-2005-018. [Link]

152 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

3.1.11 Vertex Cover

Functions for computing an approximate minimum weight vertex cover.


A vertex cover is a subset of nodes such that each edge in the graph is incident to at least one node in the subset.

min_weighted_vertex_cover(G[, weight]) Returns an approximate minimum weighted vertex


cover.

[Link].vertex_cover.min_weighted_vertex_cover

min_weighted_vertex_cover(G, weight=None)
Returns an approximate minimum weighted vertex cover.
The set of nodes returned by this function is guaranteed to be a vertex cover, and the total weight of the set is
guaranteed to be at most twice the total weight of the minimum weight vertex cover. In other words,

𝑤(𝑆) ≤ 2 * 𝑤(𝑆 * ),

where 𝑆 is the vertex cover returned by this function, 𝑆 * is the vertex cover of minimum weight out of all vertex
covers of the graph, and 𝑤 is the function that computes the sum of the weights of each node in that given set.
Parameters
• G (NetworkX graph)
• weight (string, optional (default = None)) – If None, every node has weight 1. If a string,
use this node attribute as the node weight. A node without this attribute is assumed to have
weight 1.
Returns min_weighted_cover – Returns a set of nodes whose weight sum is no more than twice
the weight sum of the minimum weight vertex cover.
Return type set

Notes

For a directed graph, a vertex cover has the same definition: a set of nodes such that each edge in the graph is
incident to at least one node in the set. Whether the node is the head or tail of the directed edge is ignored.
This is the local-ratio algorithm for computing an approximate vertex cover. The algorithm greedily reduces
the costs over edges, iteratively building a cover. The worst-case runtime of this implementation is 𝑂(𝑚 log 𝑛),
where 𝑛 is the number of nodes and 𝑚 the number of edges in the graph.

References

3.2 Assortativity

3.2. Assortativity 153


NetworkX Reference, Release 2.5

3.2.1 Assortativity

degree_assortativity_coefficient(G[, x, Compute degree assortativity of graph.


y, . . . ])
attribute_assortativity_coefficient(G, Compute assortativity for node attributes.
attribute)
numeric_assortativity_coefficient(G, Compute assortativity for numerical node attributes.
attribute)
Compute degree assortativity of graph.
degree_pearson_correlation_coefficient(G[,
. . . ])

[Link].degree_assortativity_coefficient

degree_assortativity_coefficient(G, x='out', y='in', weight=None, nodes=None)


Compute degree assortativity of graph.
Assortativity measures the similarity of connections in the graph with respect to the node degree.
Parameters
• G (NetworkX graph)
• x (string (‘in’,’out’)) – The degree type for source node (directed graphs only).
• y (string (‘in’,’out’)) – The degree type for target node (directed graphs only).
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical value used as a weight. If None, then each edge has weight 1. The degree is the sum of
the edge weights adjacent to the node.
• nodes (list or iterable (optional)) – Compute degree assortativity only for nodes in container.
The default is all nodes.
Returns r – Assortativity of graph by degree.
Return type float

Examples

>>> G = nx.path_graph(4)
>>> r = nx.degree_assortativity_coefficient(G)
>>> print(f"{r:3.1f}")
-0.5

See also:
attribute_assortativity_coefficient(), numeric_assortativity_coefficient(),
neighbor_connectivity(), degree_mixing_dict(), degree_mixing_matrix()

154 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Notes

This computes Eq. (21) in Ref.1 , where e is the joint probability distribution (mixing matrix) of the degrees. If
G is directed than the matrix e is the joint probability of the user-specified degree type for the source and target.

References

[Link].attribute_assortativity_coefficient

attribute_assortativity_coefficient(G, attribute, nodes=None)


Compute assortativity for node attributes.
Assortativity measures the similarity of connections in the graph with respect to the given attribute.
Parameters
• G (NetworkX graph)
• attribute (string) – Node attribute key
• nodes (list or iterable (optional)) – Compute attribute assortativity for nodes in container.
The default is all nodes.
Returns r – Assortativity of graph for given attribute
Return type float

Examples

>>> G = [Link]()
>>> G.add_nodes_from([0, 1], color="red")
>>> G.add_nodes_from([2, 3], color="blue")
>>> G.add_edges_from([(0, 1), (2, 3)])
>>> print(nx.attribute_assortativity_coefficient(G, "color"))
1.0

Notes

This computes Eq. (2) in Ref.1 , (trace(M)-sum(M^2))/(1-sum(M^2)), where M is the joint probability distribu-
tion (mixing matrix) of the specified attribute.

References

[Link].numeric_assortativity_coefficient

numeric_assortativity_coefficient(G, attribute, nodes=None)


Compute assortativity for numerical node attributes.
Assortativity measures the similarity of connections in the graph with respect to the given numeric attribute.
The numeric attribute must be an integer.
Parameters
1 M. E. J. Newman, Mixing patterns in networks, Physical Review E, 67 026126, 2003
1 M. E. J. Newman, Mixing patterns in networks, Physical Review E, 67 026126, 2003

3.2. Assortativity 155


NetworkX Reference, Release 2.5

• G (NetworkX graph)
• attribute (string) – Node attribute key. The corresponding attribute value must be an integer.
• nodes (list or iterable (optional)) – Compute numeric assortativity only for attributes of
nodes in container. The default is all nodes.
Returns r – Assortativity of graph for given attribute
Return type float

Examples

>>> G = [Link]()
>>> G.add_nodes_from([0, 1], size=2)
>>> G.add_nodes_from([2, 3], size=3)
>>> G.add_edges_from([(0, 1), (2, 3)])
>>> print(nx.numeric_assortativity_coefficient(G, "size"))
1.0

Notes

This computes Eq. (21) in Ref.1 , for the mixing matrix of of the specified attribute.

References

[Link].degree_pearson_correlation_coefficient

degree_pearson_correlation_coefficient(G, x='out', y='in', weight=None, nodes=None)


Compute degree assortativity of graph.
Assortativity measures the similarity of connections in the graph with respect to the node degree.
This is the same as degree_assortativity_coefficient but uses the potentially faster [Link] function.
Parameters
• G (NetworkX graph)
• x (string (‘in’,’out’)) – The degree type for source node (directed graphs only).
• y (string (‘in’,’out’)) – The degree type for target node (directed graphs only).
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical value used as a weight. If None, then each edge has weight 1. The degree is the sum of
the edge weights adjacent to the node.
• nodes (list or iterable (optional)) – Compute pearson correlation of degrees only for speci-
fied nodes. The default is all nodes.
Returns r – Assortativity of graph by degree.
Return type float
1 M. E. J. Newman, Mixing patterns in networks Physical Review E, 67 026126, 2003

156 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Examples

>>> G = nx.path_graph(4)
>>> r = nx.degree_pearson_correlation_coefficient(G)
>>> print(f"{r:3.1f}")
-0.5

Notes

This calls [Link].

References

3.2.2 Average neighbor degree

average_neighbor_degree(G[, source, target, Returns the average degree of the neighborhood of each
. . . ]) node.

[Link].average_neighbor_degree

average_neighbor_degree(G, source='out', target='out', nodes=None, weight=None)


Returns the average degree of the neighborhood of each node.
The average neighborhood degree of a node i is
1 ∑︁
𝑘𝑛𝑛,𝑖 = 𝑘𝑗
|𝑁 (𝑖)|
𝑗∈𝑁 (𝑖)

where N(i) are the neighbors of node i and k_j is the degree of node j which belongs to N(i). For weighted
graphs, an analogous measure can be defined1 ,

𝑤 1 ∑︁
𝑘𝑛𝑛,𝑖 = 𝑤𝑖𝑗 𝑘𝑗
𝑠𝑖
𝑗∈𝑁 (𝑖)

where s_i is the weighted degree of node i, w_{ij} is the weight of the edge that links i and j and N(i)
are the neighbors of node i.
Parameters
• G (NetworkX graph)
• source (string (“in”|”out”)) – Directed graphs only. Use “in”- or “out”-degree for source
node.
• target (string (“in”|”out”)) – Directed graphs only. Use “in”- or “out”-degree for target
node.
• nodes (list or iterable, optional) – Compute neighbor degree for specified nodes. The default
is all nodes in the graph.
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical value used as a weight. If None, then each edge has weight 1.
1A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani, “The architecture of complex weighted networks”. PNAS 101 (11):
3747–3752 (2004).

3.2. Assortativity 157


NetworkX Reference, Release 2.5

Returns d – A dictionary keyed by node with average neighbors degree value.


Return type dict

Examples

>>> G = nx.path_graph(4)
>>> [Link][0, 1]["weight"] = 5
>>> [Link][2, 3]["weight"] = 3

>>> nx.average_neighbor_degree(G)
{0: 2.0, 1: 1.5, 2: 1.5, 3: 2.0}
>>> nx.average_neighbor_degree(G, weight="weight")
{0: 2.0, 1: 1.1666666666666667, 2: 1.25, 3: 2.0}

>>> G = [Link]()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> nx.average_neighbor_degree(G, source="in", target="in")
{0: 1.0, 1: 1.0, 2: 1.0, 3: 0.0}

>>> nx.average_neighbor_degree(G, source="out", target="out")


{0: 1.0, 1: 1.0, 2: 0.0, 3: 0.0}

Notes

For directed graphs you can also specify in-degree or out-degree by passing keyword arguments.
See also:
average_degree_connectivity()

References

3.2.3 Average degree connectivity

average_degree_connectivity(G[, source, Compute the average degree connectivity of graph.


. . . ])
k_nearest_neighbors(G[, source, target, . . . ]) Compute the average degree connectivity of graph.

[Link].average_degree_connectivity

average_degree_connectivity(G, source='in+out', target='in+out', nodes=None, weight=None)


Compute the average degree connectivity of graph.
The average degree connectivity is the average nearest neighbor degree of nodes with degree k. For weighted
graphs, an analogous measure can be computed using the weighted average neighbors degree defined in1 , for a
1 A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani, “The architecture of complex weighted networks”. PNAS 101 (11):

3747–3752 (2004).

158 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

node i, as

𝑤 1 ∑︁
𝑘𝑛𝑛,𝑖 = 𝑤𝑖𝑗 𝑘𝑗
𝑠𝑖
𝑗∈𝑁 (𝑖)

where s_i is the weighted degree of node i, w_{ij} is the weight of the edge that links i and j, and N(i)
are the neighbors of node i.
Parameters
• G (NetworkX graph)
• source (“in”|”out”|”in+out” (default:”in+out”)) – Directed graphs only. Use “in”- or
“out”-degree for source node.
• target (“in”|”out”|”in+out” (default:”in+out”) – Directed graphs only. Use “in”- or
“out”-degree for target node.
• nodes (list or iterable (optional)) – Compute neighbor connectivity for these nodes. The
default is all nodes.
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical value used as a weight. If None, then each edge has weight 1.
Returns d – A dictionary keyed by degree k with the value of average connectivity.
Return type dict
Raises ValueError – If either source or target are not one of ‘in’, ‘out’, or ‘in+out’.

Examples

>>> G = nx.path_graph(4)
>>> [Link][1, 2]["weight"] = 3
>>> nx.k_nearest_neighbors(G)
{1: 2.0, 2: 1.5}
>>> nx.k_nearest_neighbors(G, weight="weight")
{1: 2.0, 2: 1.75}

See also:
neighbors_average_degree()

Notes

This algorithm is sometimes called “k nearest neighbors” and is also available as k_nearest_neighbors.

References

[Link].k_nearest_neighbors

k_nearest_neighbors(G, source='in+out', target='in+out', nodes=None, weight=None)


Compute the average degree connectivity of graph.
The average degree connectivity is the average nearest neighbor degree of nodes with degree k. For weighted
graphs, an analogous measure can be computed using the weighted average neighbors degree defined in1 , for a
1A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani, “The architecture of complex weighted networks”. PNAS 101 (11):
3747–3752 (2004).

3.2. Assortativity 159


NetworkX Reference, Release 2.5

node i, as

𝑤 1 ∑︁
𝑘𝑛𝑛,𝑖 = 𝑤𝑖𝑗 𝑘𝑗
𝑠𝑖
𝑗∈𝑁 (𝑖)

where s_i is the weighted degree of node i, w_{ij} is the weight of the edge that links i and j, and N(i)
are the neighbors of node i.
Parameters
• G (NetworkX graph)
• source (“in”|”out”|”in+out” (default:”in+out”)) – Directed graphs only. Use “in”- or
“out”-degree for source node.
• target (“in”|”out”|”in+out” (default:”in+out”) – Directed graphs only. Use “in”- or
“out”-degree for target node.
• nodes (list or iterable (optional)) – Compute neighbor connectivity for these nodes. The
default is all nodes.
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical value used as a weight. If None, then each edge has weight 1.
Returns d – A dictionary keyed by degree k with the value of average connectivity.
Return type dict
Raises ValueError – If either source or target are not one of ‘in’, ‘out’, or ‘in+out’.

Examples

>>> G = nx.path_graph(4)
>>> [Link][1, 2]["weight"] = 3
>>> nx.k_nearest_neighbors(G)
{1: 2.0, 2: 1.5}
>>> nx.k_nearest_neighbors(G, weight="weight")
{1: 2.0, 2: 1.75}

See also:
neighbors_average_degree()

Notes

This algorithm is sometimes called “k nearest neighbors” and is also available as k_nearest_neighbors.

References

3.2.4 Mixing

attribute_mixing_matrix(G, attribute[, . . . ]) Returns mixing matrix for attribute.


degree_mixing_matrix(G[, x, y, weight, . . . ]) Returns mixing matrix for attribute.
numeric_mixing_matrix(G, attribute[, nodes, Returns numeric mixing matrix for attribute.
. . . ])
continues on next page

160 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Table 16 – continued from previous page


attribute_mixing_dict(G, attribute[, nodes, Returns dictionary representation of mixing matrix for
. . . ]) attribute.
degree_mixing_dict(G[, x, y, weight, nodes, Returns dictionary representation of mixing matrix for
. . . ]) degree.
mixing_dict(xy[, normalized]) Returns a dictionary representation of mixing matrix.

[Link].attribute_mixing_matrix

attribute_mixing_matrix(G, attribute, nodes=None, mapping=None, normalized=True)


Returns mixing matrix for attribute.
Parameters
• G (graph) – NetworkX graph object.
• attribute (string) – Node attribute key.
• nodes (list or iterable (optional)) – Use only nodes in container to build the matrix. The
default is all nodes.
• mapping (dictionary, optional) – Mapping from node attribute to integer index in matrix. If
not specified, an arbitrary ordering will be used.
• normalized (bool (default=True)) – Return counts if False or probabilities if True.
Returns m – Counts or joint probability of occurrence of attribute pairs.
Return type numpy array

[Link].degree_mixing_matrix

degree_mixing_matrix(G, x='out', y='in', weight=None, nodes=None, normalized=True)


Returns mixing matrix for attribute.
Parameters
• G (graph) – NetworkX graph object.
• x (string (‘in’,’out’)) – The degree type for source node (directed graphs only).
• y (string (‘in’,’out’)) – The degree type for target node (directed graphs only).
• nodes (list or iterable (optional)) – Build the matrix using only nodes in container. The
default is all nodes.
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical value used as a weight. If None, then each edge has weight 1. The degree is the sum of
the edge weights adjacent to the node.
• normalized (bool (default=True)) – Return counts if False or probabilities if True.
Returns m – Counts, or joint probability, of occurrence of node degree.
Return type numpy array

3.2. Assortativity 161


NetworkX Reference, Release 2.5

[Link].numeric_mixing_matrix

numeric_mixing_matrix(G, attribute, nodes=None, normalized=True)


Returns numeric mixing matrix for attribute.
The attribute must be an integer.
Parameters
• G (graph) – NetworkX graph object.
• attribute (string) – Node attribute key. The corresponding attribute must be an integer.
• nodes (list or iterable (optional)) – Build the matrix only with nodes in container. The
default is all nodes.
• normalized (bool (default=True)) – Return counts if False or probabilities if True.
Returns m – Counts, or joint, probability of occurrence of node attribute pairs.
Return type numpy array

[Link].attribute_mixing_dict

attribute_mixing_dict(G, attribute, nodes=None, normalized=False)


Returns dictionary representation of mixing matrix for attribute.
Parameters
• G (graph) – NetworkX graph object.
• attribute (string) – Node attribute key.
• nodes (list or iterable (optional)) – Unse nodes in container to build the dict. The default is
all nodes.
• normalized (bool (default=False)) – Return counts if False or probabilities if True.

Examples

>>> G = [Link]()
>>> G.add_nodes_from([0, 1], color="red")
>>> G.add_nodes_from([2, 3], color="blue")
>>> G.add_edge(1, 3)
>>> d = nx.attribute_mixing_dict(G, "color")
>>> print(d["red"]["blue"])
1
>>> print(d["blue"]["red"]) # d symmetric for undirected graphs
1

Returns d – Counts or joint probability of occurrence of attribute pairs.


Return type dictionary

162 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

[Link].degree_mixing_dict

degree_mixing_dict(G, x='out', y='in', weight=None, nodes=None, normalized=False)


Returns dictionary representation of mixing matrix for degree.
Parameters
• G (graph) – NetworkX graph object.
• x (string (‘in’,’out’)) – The degree type for source node (directed graphs only).
• y (string (‘in’,’out’)) – The degree type for target node (directed graphs only).
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical value used as a weight. If None, then each edge has weight 1. The degree is the sum of
the edge weights adjacent to the node.
• normalized (bool (default=False)) – Return counts if False or probabilities if True.
Returns d – Counts or joint probability of occurrence of degree pairs.
Return type dictionary

[Link].mixing_dict

mixing_dict(xy, normalized=False)
Returns a dictionary representation of mixing matrix.
Parameters
• xy (list or container of two-tuples) – Pairs of (x,y) items.
• attribute (string) – Node attribute key
• normalized (bool (default=False)) – Return counts if False or probabilities if True.
Returns d – Counts or Joint probability of occurrence of values in xy.
Return type dictionary

3.2.5 Pairs

node_attribute_xy(G, attribute[, nodes]) Returns iterator of node-attribute pairs for all edges in
G.
node_degree_xy(G[, x, y, weight, nodes]) Generate node degree-degree pairs for edges in G.

[Link].node_attribute_xy

node_attribute_xy(G, attribute, nodes=None)


Returns iterator of node-attribute pairs for all edges in G.
Parameters
• G (NetworkX graph)
• attribute (key) – The node attribute key.
• nodes (list or iterable (optional)) – Use only edges that are adjacency to specified nodes.
The default is all nodes.

3.2. Assortativity 163


NetworkX Reference, Release 2.5

Returns (x,y) – Generates 2-tuple of (attribute,attribute) values.


Return type 2-tuple

Examples

>>> G = [Link]()
>>> G.add_node(1, color="red")
>>> G.add_node(2, color="blue")
>>> G.add_edge(1, 2)
>>> list(nx.node_attribute_xy(G, "color"))
[('red', 'blue')]

Notes

For undirected graphs each edge is produced twice, once for each edge representation (u,v) and (v,u), with the
exception of self-loop edges which only appear once.

[Link].node_degree_xy

node_degree_xy(G, x='out', y='in', weight=None, nodes=None)


Generate node degree-degree pairs for edges in G.
Parameters
• G (NetworkX graph)
• x (string (‘in’,’out’)) – The degree type for source node (directed graphs only).
• y (string (‘in’,’out’)) – The degree type for target node (directed graphs only).
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical value used as a weight. If None, then each edge has weight 1. The degree is the sum of
the edge weights adjacent to the node.
• nodes (list or iterable (optional)) – Use only edges that are adjacency to specified nodes.
The default is all nodes.
Returns (x,y) – Generates 2-tuple of (degree,degree) values.
Return type 2-tuple

Examples

>>> G = [Link]()
>>> G.add_edge(1, 2)
>>> list(nx.node_degree_xy(G, x="out", y="in"))
[(1, 1)]
>>> list(nx.node_degree_xy(G, x="in", y="out"))
[(0, 0)]

164 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Notes

For undirected graphs each edge is produced twice, once for each edge representation (u,v) and (v,u), with the
exception of self-loop edges which only appear once.

3.3 Asteroidal

Algorithms for asteroidal triples and asteroidal numbers in graphs.


An asteroidal triple in a graph G is a set of three non-adjacent vertices u, v and w such that there exist a path between
any two of them that avoids closed neighborhood of the third. More formally, v_j, v_k belongs to the same connected
component of G - N[v_i], where N[v_i] denotes the closed neighborhood of v_i. A graph which does not contain any
asteroidal triples is called an AT-free graph. The class of AT-free graphs is a graph class for which many NP-complete
problems are solvable in polynomial time. Amongst them, independent set and coloring.

is_at_free(G) Check if a graph is AT-free.


find_asteroidal_triple(G) Find an asteroidal triple in the given graph.

3.3.1 [Link].is_at_free

is_at_free(G)
Check if a graph is AT-free.
The method uses the find_asteroidal_triple method to recognize an AT-free graph. If no asteroidal
triple is found the graph is AT-free and True is returned. If at least one asteroidal triple is found the graph is not
AT-free and False is returned.
Parameters G (NetworkX Graph) – The graph to check whether is AT-free or not.
Returns True if G is AT-free and False otherwise.
Return type bool

Examples

>>> G = [Link]([(0, 1), (0, 2), (1, 2), (1, 3), (1, 4), (4, 5)])
>>> nx.is_at_free(G)
True

>>> G = nx.cycle_graph(6)
>>> nx.is_at_free(G)
False

3.3. Asteroidal 165


NetworkX Reference, Release 2.5

3.3.2 [Link].find_asteroidal_triple

find_asteroidal_triple(G)
Find an asteroidal triple in the given graph.
An asteroidal triple is a triple of non-adjacent vertices such that there exists a path between any two of them
which avoids the closed neighborhood of the third. It checks all independent triples of vertices and whether
they are an asteroidal triple or not. This is done with the help of a data structure called a component structure.
A component structure encodes information about which vertices belongs to the same connected component
when the closed neighborhood of a given vertex is removed from the graph. The algorithm used to check is the
trivial one, outlined in1 , which has a runtime of 𝑂(|𝑉 ||𝐸 + |𝑉 ||𝐸|), where the second term is the creation of
the component structure.
Parameters G (NetworkX Graph) – The graph to check whether is AT-free or not
Returns An asteroidal triple is returned as a list of nodes. If no asteroidal triple exists, i.e. the graph
is AT-free, then None is returned. The returned value depends on the certificate parameter. The
default option is a bool which is True if the graph is AT-free, i.e. the given graph contains no
asteroidal triples, and False otherwise, i.e. if the graph contains at least one asteroidal triple.
Return type list or None

Notes

The component structure and the algorithm is described in1 . The current implementation implements the trivial
algorithm for simple graphs.

References

3.4 Bipartite

This module provides functions and operations for bipartite graphs. Bipartite graphs B = (U, V, E) have two
node sets U,V and edges in E that only connect nodes from opposite sets. It is common in the literature to use an
spatial analogy referring to the two node sets as top and bottom nodes.
The bipartite algorithms are not imported into the networkx namespace at the top level so the easiest way to use them
is with:

>>> from [Link] import bipartite

NetworkX does not have a custom bipartite graph class but the Graph() or DiGraph() classes can be used to represent
bipartite graphs. However, you have to keep track of which set each node belongs to, and make sure that there is no
edge between nodes of the same set. The convention used in NetworkX is to use a node attribute named bipartite
with values 0 or 1 to identify the sets each node belongs to. This convention is not enforced in the source code of
bipartite functions, it’s only a recommendation.
For example:

>>> B = [Link]()
>>> # Add nodes with the node attribute "bipartite"
>>> B.add_nodes_from([1, 2, 3, 4], bipartite=0)
>>> B.add_nodes_from(["a", "b", "c"], bipartite=1)
(continues on next page)
1 Ekkehard Köhler, “Recognizing Graphs without asteroidal triples”, Journal of Discrete Algorithms 2, pages 439-452, 2004. [Link]

[Link]/science/article/pii/S157086670400019X

166 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

(continued from previous page)


>>> # Add edges only between nodes of opposite node sets
>>> B.add_edges_from([(1, "a"), (1, "b"), (2, "b"), (2, "c"), (3, "c"), (4, "a")])

Many algorithms of the bipartite module of NetworkX require, as an argument, a container with all the nodes that
belong to one set, in addition to the bipartite graph B. The functions in the bipartite package do not check that the node
set is actually correct nor that the input graph is actually bipartite. If B is connected, you can find the two node sets
using a two-coloring algorithm:

>>> nx.is_connected(B)
True
>>> bottom_nodes, top_nodes = [Link](B)

However, if the input graph is not connected, there are more than one possible colorations. This is the reason why we
require the user to pass a container with all nodes of one bipartite node set as an argument to most bipartite functions.
In the face of ambiguity, we refuse the temptation to guess and raise an AmbiguousSolution Exception if the
input graph for [Link] is disconnected.
Using the bipartite node attribute, you can easily get the two node sets:

>>> top_nodes = {n for n, d in [Link](data=True) if d["bipartite"] == 0}


>>> bottom_nodes = set(B) - top_nodes

So you can easily use the bipartite algorithms that require, as an argument, a container with all nodes that belong to
one node set:

>>> print(round([Link](B, bottom_nodes), 2))


0.5
>>> G = bipartite.projected_graph(B, top_nodes)

All bipartite graph generators in NetworkX build bipartite graphs with the bipartite node attribute. Thus, you can
use the same approach:

>>> RB = bipartite.random_graph(5, 7, 0.2)


>>> RB_top = {n for n, d in [Link](data=True) if d["bipartite"] == 0}
>>> RB_bottom = set(RB) - RB_top
>>> list(RB_top)
[0, 1, 2, 3, 4]
>>> list(RB_bottom)
[5, 6, 7, 8, 9, 10, 11]

For other bipartite graph generators see Generators.

3.4.1 Basic functions

Bipartite Graph Algorithms

is_bipartite(G) Returns True if graph G is bipartite, False if not.


is_bipartite_node_set(G, nodes) Returns True if nodes and G/nodes are a bipartition of
G.
sets(G[, top_nodes]) Returns bipartite node sets of graph G.
color(G) Returns a two-coloring of the graph.
density(B, nodes) Returns density of bipartite graph B.
continues on next page

3.4. Bipartite 167


NetworkX Reference, Release 2.5

Table 19 – continued from previous page


degrees(B, nodes[, weight]) Returns the degrees of the two node sets in the bipartite
graph B.

[Link].is_bipartite

is_bipartite(G)
Returns True if graph G is bipartite, False if not.
Parameters G (NetworkX graph)

Examples

>>> from [Link] import bipartite


>>> G = nx.path_graph(4)
>>> print(bipartite.is_bipartite(G))
True

See also:
color(), is_bipartite_node_set()

[Link].is_bipartite_node_set

is_bipartite_node_set(G, nodes)
Returns True if nodes and G/nodes are a bipartition of G.
Parameters
• G (NetworkX graph)
• nodes (list or container) – Check if nodes are a one of a bipartite set.

Examples

>>> from [Link] import bipartite


>>> G = nx.path_graph(4)
>>> X = set([1, 3])
>>> bipartite.is_bipartite_node_set(G, X)
True

Notes

For connected graphs the bipartite sets are unique. This function handles disconnected graphs.

168 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

[Link]

sets(G, top_nodes=None)
Returns bipartite node sets of graph G.
Raises an exception if the graph is not bipartite or if the input graph is disconnected and thus more than one valid
solution exists. See bipartite documentation for further details on how bipartite graphs are handled in
NetworkX.
Parameters
• G (NetworkX graph)
• top_nodes (container, optional) – Container with all nodes in one bipartite node set. If not
supplied it will be computed. But if more than one solution exists an exception will be
raised.
Returns
• X (set) – Nodes from one side of the bipartite graph.
• Y (set) – Nodes from the other side.
Raises
• AmbiguousSolution – Raised if the input bipartite graph is disconnected and no con-
tainer with all nodes in one bipartite set is provided. When determining the nodes in each
bipartite set more than one valid solution is possible if the input graph is disconnected.
• NetworkXError – Raised if the input graph is not bipartite.

Examples

>>> from [Link] import bipartite


>>> G = nx.path_graph(4)
>>> X, Y = [Link](G)
>>> list(X)
[0, 2]
>>> list(Y)
[1, 3]

See also:
color()

[Link]

color(G)
Returns a two-coloring of the graph.
Raises an exception if the graph is not bipartite.
Parameters G (NetworkX graph)
Returns color – A dictionary keyed by node with a 1 or 0 as data for each node color.
Return type dictionary
Raises NetworkXError – If the graph is not two-colorable.

3.4. Bipartite 169


NetworkX Reference, Release 2.5

Examples

>>> from [Link] import bipartite


>>> G = nx.path_graph(4)
>>> c = [Link](G)
>>> print(c)
{0: 1, 1: 0, 2: 1, 3: 0}

You can use this to set a node attribute indicating the biparite set:

>>> nx.set_node_attributes(G, c, "bipartite")


>>> print([Link][0]["bipartite"])
1
>>> print([Link][1]["bipartite"])
0

[Link]

density(B, nodes)
Returns density of bipartite graph B.
Parameters
• G (NetworkX graph)
• nodes (list or container) – Nodes in one node set of the bipartite graph.
Returns d – The bipartite density
Return type float

Examples

>>> from [Link] import bipartite


>>> G = nx.complete_bipartite_graph(3, 2)
>>> X = set([0, 1, 2])
>>> [Link](G, X)
1.0
>>> Y = set([3, 4])
>>> [Link](G, Y)
1.0

Notes

The container of nodes passed as argument must contain all nodes in one of the two bipartite node sets to avoid
ambiguity in the case of disconnected graphs. See bipartite documentation for further details on how
bipartite graphs are handled in NetworkX.
See also:
color()

170 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

[Link]

degrees(B, nodes, weight=None)


Returns the degrees of the two node sets in the bipartite graph B.
Parameters
• G (NetworkX graph)
• nodes (list or container) – Nodes in one node set of the bipartite graph.
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical value used as a weight. If None, then each edge has weight 1. The degree is the sum of
the edge weights adjacent to the node.
Returns (degX,degY) – The degrees of the two bipartite sets as dictionaries keyed by node.
Return type tuple of dictionaries

Examples

>>> from [Link] import bipartite


>>> G = nx.complete_bipartite_graph(3, 2)
>>> Y = set([3, 4])
>>> degX, degY = [Link](G, Y)
>>> dict(degX)
{0: 2, 1: 2, 2: 2}

Notes

The container of nodes passed as argument must contain all nodes in one of the two bipartite node sets to avoid
ambiguity in the case of disconnected graphs. See bipartite documentation for further details on how
bipartite graphs are handled in NetworkX.
See also:
color(), density()

3.4.2 Edgelist

Bipartite Edge Lists

Read and write NetworkX graphs as bipartite edge lists.

Format

You can read or write three formats of edge lists with these functions.
Node pairs with no data:

1 2

Python dictionary as data:

3.4. Bipartite 171


NetworkX Reference, Release 2.5

1 2 {'weight':7, 'color':'green'}

Arbitrary data:

1 2 7 green

For each edge (u, v) the node u is assigned to part 0 and the node v to part 1.

generate_edgelist(G[, delimiter, data]) Generate a single line of the bipartite graph G in edge
list format.
write_edgelist(G, path[, comments, . . . ]) Write a bipartite graph as a list of edges.
parse_edgelist(lines[, comments, delimiter, . . . ]) Parse lines of an edge list representation of a bipartite
graph.
read_edgelist(path[, comments, delimiter, . . . ]) Read a bipartite graph from a list of edges.

[Link].generate_edgelist

generate_edgelist(G, delimiter=' ', data=True)


Generate a single line of the bipartite graph G in edge list format.
Parameters
• G (NetworkX graph) – The graph is assumed to have node attribute part set to 0,1 repre-
senting the two graph parts
• delimiter (string, optional) – Separator for node labels
• data (bool or list of keys) – If False generate no edge data. If True use a dictionary repre-
sentation of edge data. If a list of keys use a list of data values corresponding to the keys.
Returns lines – Lines of data in adjlist format.
Return type string

Examples

>>> from [Link] import bipartite


>>> G = nx.path_graph(4)
>>> G.add_nodes_from([0, 2], bipartite=0)
>>> G.add_nodes_from([1, 3], bipartite=1)
>>> G[1][2]["weight"] = 3
>>> G[2][3]["capacity"] = 12
>>> for line in bipartite.generate_edgelist(G, data=False):
... print(line)
0 1
2 1
2 3

>>> for line in bipartite.generate_edgelist(G):


... print(line)
0 1 {}
2 1 {'weight': 3}
2 3 {'capacity': 12}

172 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

>>> for line in bipartite.generate_edgelist(G, data=["weight"]):


... print(line)
0 1
2 1 3
2 3

[Link].write_edgelist

write_edgelist(G, path, comments='#', delimiter=' ', data=True, encoding='utf-8')


Write a bipartite graph as a list of edges.
Parameters
• G (Graph) – A NetworkX bipartite graph
• path (file or string) – File or filename to write. If a file is provided, it must be opened in
‘wb’ mode. Filenames ending in .gz or .bz2 will be compressed.
• comments (string, optional) – The character used to indicate the start of a comment
• delimiter (string, optional) – The string used to separate values. The default is whitespace.
• data (bool or list, optional) – If False write no edge data. If True write a string representation
of the edge data dictionary.. If a list (or other iterable) is provided, write the keys specified
in the list.
• encoding (string, optional) – Specify which encoding to use when writing file.

Examples

>>> G = nx.path_graph(4)
>>> G.add_nodes_from([0, 2], bipartite=0)
>>> G.add_nodes_from([1, 3], bipartite=1)
>>> nx.write_edgelist(G, "[Link]")
>>> fh = open("[Link]", "wb")
>>> nx.write_edgelist(G, fh)
>>> nx.write_edgelist(G, "[Link]")
>>> nx.write_edgelist(G, "[Link]", data=False)

>>> G = [Link]()
>>> G.add_edge(1, 2, weight=7, color="red")
>>> nx.write_edgelist(G, "[Link]", data=False)
>>> nx.write_edgelist(G, "[Link]", data=["color"])
>>> nx.write_edgelist(G, "[Link]", data=["color", "weight"])

See also:
write_edgelist(), generate_edgelist()

3.4. Bipartite 173


NetworkX Reference, Release 2.5

[Link].parse_edgelist

parse_edgelist(lines, comments='#', delimiter=None, create_using=None, nodetype=None, data=True)


Parse lines of an edge list representation of a bipartite graph.
Parameters
• lines (list or iterator of strings) – Input data in edgelist format
• comments (string, optional) – Marker for comment lines
• delimiter (string, optional) – Separator for node labels
• create_using (NetworkX graph container, optional) – Use given NetworkX graph for hold-
ing nodes or edges.
• nodetype (Python type, optional) – Convert nodes to this type.
• data (bool or list of (label,type) tuples) – If False generate no edge data or if True use a
dictionary representation of edge data or a list tuples specifying dictionary key names and
types for edge data.
Returns G – The bipartite graph corresponding to lines
Return type NetworkX Graph

Examples

Edgelist with no data:

>>> from [Link] import bipartite


>>> lines = ["1 2", "2 3", "3 4"]
>>> G = bipartite.parse_edgelist(lines, nodetype=int)
>>> sorted([Link]())
[1, 2, 3, 4]
>>> sorted([Link](data=True))
[(1, {'bipartite': 0}), (2, {'bipartite': 0}), (3, {'bipartite': 0}), (4, {
˓→'bipartite': 1})]

>>> sorted([Link]())
[(1, 2), (2, 3), (3, 4)]

Edgelist with data in Python dictionary representation:

>>> lines = ["1 2 {'weight':3}", "2 3 {'weight':27}", "3 4 {'weight':3.0}"]


>>> G = bipartite.parse_edgelist(lines, nodetype=int)
>>> sorted([Link]())
[1, 2, 3, 4]
>>> sorted([Link](data=True))
[(1, 2, {'weight': 3}), (2, 3, {'weight': 27}), (3, 4, {'weight': 3.0})]

Edgelist with data in a list:

>>> lines = ["1 2 3", "2 3 27", "3 4 3.0"]


>>> G = bipartite.parse_edgelist(lines, nodetype=int, data=(("weight", float),))
>>> sorted([Link]())
[1, 2, 3, 4]
>>> sorted([Link](data=True))
[(1, 2, {'weight': 3.0}), (2, 3, {'weight': 27.0}), (3, 4, {'weight': 3.0})]

174 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

[Link].read_edgelist

read_edgelist(path, comments='#', delimiter=None, create_using=None, nodetype=None, data=True,


edgetype=None, encoding='utf-8')
Read a bipartite graph from a list of edges.
Parameters
• path (file or string) – File or filename to read. If a file is provided, it must be opened in ‘rb’
mode. Filenames ending in .gz or .bz2 will be uncompressed.
• comments (string, optional) – The character used to indicate the start of a comment.
• delimiter (string, optional) – The string used to separate values. The default is whitespace.
• create_using (Graph container, optional,) – Use specified container to build graph. The
default is [Link], an undirected graph.
• nodetype (int, float, str, Python type, optional) – Convert node data from strings to specified
type
• data (bool or list of (label,type) tuples) – Tuples specifying dictionary key names and types
for edge data
• edgetype (int, float, str, Python type, optional OBSOLETE) – Convert edge data from strings
to specified type and use as ‘weight’
• encoding (string, optional) – Specify which encoding to use when reading file.
Returns G – A networkx Graph or other type specified with create_using
Return type graph

Examples

>>> from [Link] import bipartite


>>> G = nx.path_graph(4)
>>> G.add_nodes_from([0, 2], bipartite=0)
>>> G.add_nodes_from([1, 3], bipartite=1)
>>> bipartite.write_edgelist(G, "[Link]")
>>> G = bipartite.read_edgelist("[Link]")

>>> fh = open("[Link]", "rb")


>>> G = bipartite.read_edgelist(fh)
>>> [Link]()

>>> G = bipartite.read_edgelist("[Link]", nodetype=int)

Edgelist with data in a list:

>>> textline = "1 2 3"


>>> fh = open("[Link]", "w")
>>> d = [Link](textline)
>>> [Link]()
>>> G = bipartite.read_edgelist(
... "[Link]", nodetype=int, data=(("weight", float),)
... )
>>> list(G)
[1, 2]
(continues on next page)

3.4. Bipartite 175


NetworkX Reference, Release 2.5

(continued from previous page)


>>> list([Link](data=True))
[(1, 2, {'weight': 3.0})]

See parse_edgelist() for more examples of formatting.


See also:
parse_edgelist()

Notes

Since nodes must be hashable, the function nodetype must return hashable types (e.g. int, float, str, frozenset -
or tuples of those, etc.)

3.4.3 Matching

Provides functions for computing maximum cardinality matchings and minimum weight full matchings in a bipartite
graph.
If you don’t care about the particular implementation of the maximum matching algorithm, simply use the
maximum_matching(). If you do care, you can import one of the named maximum matching algorithms directly.
For example, to find a maximum matching in the complete bipartite graph with two vertices on the left and three
vertices on the right:

>>> G = nx.complete_bipartite_graph(2, 3)
>>> left, right = [Link](G)
>>> list(left)
[0, 1]
>>> list(right)
[2, 3, 4]
>>> [Link].maximum_matching(G)
{0: 2, 1: 3, 2: 0, 3: 1}

The dictionary returned by maximum_matching() includes a mapping for vertices in both the left and right vertex
sets.
Similarly, minimum_weight_full_matching() produces, for a complete weighted bipartite graph, a matching
whose cardinality is the cardinality of the smaller of the two partitions, and for which the sum of the weights of the
edges included in the matching is minimal.

eppstein_matching(G[, top_nodes]) Returns the maximum cardinality matching of the bipar-


tite graph G.
hopcroft_karp_matching(G[, top_nodes]) Returns the maximum cardinality matching of the bipar-
tite graph G.
to_vertex_cover(G, matching[, top_nodes]) Returns the minimum vertex cover corresponding to the
given maximum matching of the bipartite graph G.
maximum_matching(G[, top_nodes]) Returns the maximum cardinality matching in the given
bipartite graph.
minimum_weight_full_matching(G[, Returns a minimum weight full matching of the bipartite
top_nodes, . . . ]) graph G.

176 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

[Link].eppstein_matching

eppstein_matching(G, top_nodes=None)
Returns the maximum cardinality matching of the bipartite graph G.
Parameters
• G (NetworkX graph) – Undirected bipartite graph
• top_nodes (container) – Container with all nodes in one bipartite node set. If not supplied
it will be computed. But if more than one solution exists an exception will be raised.
Returns matches – The matching is returned as a dictionary, matching, such that matching[v]
== w if node v is matched to node w. Unmatched nodes do not occur as a key in matching.
Return type dictionary
Raises AmbiguousSolution – Raised if the input bipartite graph is disconnected and no con-
tainer with all nodes in one bipartite set is provided. When determining the nodes in each
bipartite set more than one valid solution is possible if the input graph is disconnected.

Notes

This function is implemented with David Eppstein’s version of the algorithm Hopcroft–Karp algorithm (see
hopcroft_karp_matching()), which originally appeared in the Python Algorithms and Data Structures
library (PADS).
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
See also:
hopcroft_karp_matching()

[Link].hopcroft_karp_matching

hopcroft_karp_matching(G, top_nodes=None)
Returns the maximum cardinality matching of the bipartite graph G.
A matching is a set of edges that do not share any nodes. A maximum cardinality matching is a matching with
the most edges possible. It is not always unique. Finding a matching in a bipartite graph can be treated as a
networkx flow problem.
The functions hopcroft_karp_matching and maximum_matching are aliases of the same function.
Parameters
• G (NetworkX graph) – Undirected bipartite graph
• top_nodes (container of nodes) – Container with all nodes in one bipartite node set. If not
supplied it will be computed. But if more than one solution exists an exception will be
raised.
Returns matches – The matching is returned as a dictionary, matches, such that matches[v]
== w if node v is matched to node w. Unmatched nodes do not occur as a key in matches.
Return type dictionary
Raises AmbiguousSolution – Raised if the input bipartite graph is disconnected and no con-
tainer with all nodes in one bipartite set is provided. When determining the nodes in each
bipartite set more than one valid solution is possible if the input graph is disconnected.

3.4. Bipartite 177


NetworkX Reference, Release 2.5

Notes

This function is implemented with the Hopcroft–Karp matching algorithm for bipartite graphs.
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
See also:
maximum_matching(), hopcroft_karp_matching(), eppstein_matching()

References

[Link].to_vertex_cover

to_vertex_cover(G, matching, top_nodes=None)


Returns the minimum vertex cover corresponding to the given maximum matching of the bipartite graph G.
Parameters
• G (NetworkX graph) – Undirected bipartite graph
• matching (dictionary) – A dictionary whose keys are vertices in G and whose values are the
distinct neighbors comprising the maximum matching for G, as returned by, for example,
maximum_matching(). The dictionary must represent the maximum matching.
• top_nodes (container) – Container with all nodes in one bipartite node set. If not supplied
it will be computed. But if more than one solution exists an exception will be raised.
Returns vertex_cover – The minimum vertex cover in G.
Return type set
Raises AmbiguousSolution – Raised if the input bipartite graph is disconnected and no con-
tainer with all nodes in one bipartite set is provided. When determining the nodes in each
bipartite set more than one valid solution is possible if the input graph is disconnected.

Notes

This function is implemented using the procedure guaranteed by Konig’s theorem, which proves an equivalence
between a maximum matching and a minimum vertex cover in bipartite graphs.
Since a minimum vertex cover is the complement of a maximum independent set for any graph, one can compute
the maximum independent set of a bipartite graph this way:

>>> G = nx.complete_bipartite_graph(2, 3)
>>> matching = [Link].maximum_matching(G)
>>> vertex_cover = [Link].to_vertex_cover(G, matching)
>>> independent_set = set(G) - vertex_cover
>>> print(list(independent_set))
[2, 3, 4]

See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.

178 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

[Link].maximum_matching

maximum_matching(G, top_nodes=None)
Returns the maximum cardinality matching in the given bipartite graph.
This function is simply an alias for hopcroft_karp_matching().

[Link].minimum_weight_full_matching

minimum_weight_full_matching(G, top_nodes=None, weight='weight')


Returns a minimum weight full matching of the bipartite graph G.
Let 𝐺 = ((𝑈, 𝑉 ), 𝐸) be a weighted bipartite graph with real weights 𝑤 : 𝐸 → R. This function then produces
a matching 𝑀 ⊆ 𝐸 with cardinality

|𝑀 | = min(|𝑈 |, |𝑉 |),
∑︀
which minimizes the sum of the weights of the edges included in the matching, 𝑒∈𝑀 𝑤(𝑒), or raises an error
if no such matching exists.
When |𝑈 | = |𝑉 |, this is commonly referred to as a perfect matching; here, since we allow |𝑈 | and |𝑉 | to differ,
we follow Karp1 and refer to the matching as full.
Parameters
• G (NetworkX graph) – Undirected bipartite graph
• top_nodes (container) – Container with all nodes in one bipartite node set. If not supplied
it will be computed.
• weight (string, optional (default=’weight’)) – The edge data key used to provide each value
in the matrix.
Returns matches – The matching is returned as a dictionary, matches, such that matches[v]
== w if node v is matched to node w. Unmatched nodes do not occur as a key in matches.
Return type dictionary
Raises
• ValueError – Raised if no full matching exists.
• ImportError – Raised if SciPy is not available.

Notes

The problem of determining a minimum weight full matching is also known as the rectangular linear assignment
problem. This implementation defers the calculation of the assignment to SciPy.
1 Richard Manning Karp: An algorithm to Solve the m x n Assignment Problem in Expected Time O(mn log n). Networks, 10(2):143–152,

1980.

3.4. Bipartite 179


NetworkX Reference, Release 2.5

References

3.4.4 Matrix

Biadjacency matrices

biadjacency_matrix(G, row_order[, . . . ]) Returns the biadjacency matrix of the bipartite graph G.


from_biadjacency_matrix(A[, create_using, Creates a new bipartite graph from a biadjacency matrix
. . . ]) given as a SciPy sparse matrix.

[Link].biadjacency_matrix

biadjacency_matrix(G, row_order, column_order=None, dtype=None, weight='weight', format='csr')


Returns the biadjacency matrix of the bipartite graph G.
Let G = (U, V, E) be a bipartite graph with node sets U = u_{1},...,u_{r} and V = v_{1},..
.,v_{s}. The biadjacency matrix1 is the r x s matrix B in which b_{i,j} = 1 if, and only if, (u_i,
v_j) in E. If the parameter weight is not None and matches the name of an edge attribute, its value is
used instead of 1.
Parameters
• G (graph) – A NetworkX graph
• row_order (list of nodes) – The rows of the matrix are ordered according to the list of nodes.
• column_order (list, optional) – The columns of the matrix are ordered according to the list
of nodes. If column_order is None, then the ordering of columns is arbitrary.
• dtype (NumPy data-type, optional) – A valid NumPy dtype used to initialize the array. If
None, then the NumPy default is used.
• weight (string or None, optional (default=’weight’)) – The edge data key used to provide
each value in the matrix. If None, then each edge has weight 1.
• format (str in {‘bsr’, ‘csr’, ‘csc’, ‘coo’, ‘lil’, ‘dia’, ‘dok’}) – The type of the matrix to be
returned (default ‘csr’). For some algorithms different implementations of sparse matrices
can perform better. See2 for details.
Returns M – Biadjacency matrix representation of the bipartite graph G.
Return type SciPy sparse matrix

Notes

No attempt is made to check that the input graph is bipartite.


For directed bipartite graphs only successors are considered as neighbors. To obtain an adjacency matrix with
ones (or weight values) for both predecessors and successors you have to generate two biadjacency matrices
where the rows of one of them are the columns of the other, and then add one to the transpose of the other.
See also:
adjacency_matrix(), from_biadjacency_matrix()
1 [Link]
2 Scipy Dev. References, “Sparse Matrices”, [Link]

180 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

References

[Link].from_biadjacency_matrix

from_biadjacency_matrix(A, create_using=None, edge_attribute='weight')


Creates a new bipartite graph from a biadjacency matrix given as a SciPy sparse matrix.
Parameters
• A (scipy sparse matrix) – A biadjacency matrix representation of a graph
• create_using (NetworkX graph) – Use specified graph for result. The default is Graph()
• edge_attribute (string) – Name of edge attribute to store matrix numeric value. The data
will have the same type as the matrix entry (int, float, (real,imag)).

Notes

The nodes are labeled with the attribute bipartite set to an integer 0 or 1 representing membership in part 0
or part 1 of the bipartite graph.
If create_using is an instance of [Link] or [Link] and the
entries of A are of type int, then this function returns a multigraph (of the same type as create_using)
with parallel edges. In this case, edge_attribute will be ignored.
See also:
biadjacency_matrix(), from_numpy_array()

References

[1] [Link]

3.4.5 Projections

One-mode (unipartite) projections of bipartite graphs.

projected_graph(B, nodes[, multigraph])Returns the projection of B onto one of its node sets.
weighted_projected_graph(B, nodes[, ratio])
Returns a weighted projection of B onto one of its node
sets.
Newman’s weighted projection of B onto one of its node
collaboration_weighted_projected_graph(B,
nodes) sets.
overlap_weighted_projected_graph(B, Overlap weighted projection of B onto one of its node
nodes[, . . . ]) sets.
generic_weighted_projected_graph(B, Weighted projection of B with a user-specified weight
nodes[, . . . ]) function.

3.4. Bipartite 181


NetworkX Reference, Release 2.5

[Link].projected_graph

projected_graph(B, nodes, multigraph=False)


Returns the projection of B onto one of its node sets.
Returns the graph G that is the projection of the bipartite graph B onto the specified nodes. They retain their
attributes and are connected in G if they have a common neighbor in B.
Parameters
• B (NetworkX graph) – The input graph should be bipartite.
• nodes (list or iterable) – Nodes to project onto (the “bottom” nodes).
• multigraph (bool (default=False)) – If True return a multigraph where the multiple edges
represent multiple shared neighbors. They edge key in the multigraph is assigned to the
label of the neighbor.
Returns Graph – A graph that is the projection onto the given nodes.
Return type NetworkX graph or multigraph

Examples

>>> from [Link] import bipartite


>>> B = nx.path_graph(4)
>>> G = bipartite.projected_graph(B, [1, 3])
>>> list(G)
[1, 3]
>>> list([Link]())
[(1, 3)]

If nodes a, and b are connected through both nodes 1 and 2 then building a multigraph results in two edges in
the projection onto [a, b]:

>>> B = [Link]()
>>> B.add_edges_from([("a", 1), ("b", 1), ("a", 2), ("b", 2)])
>>> G = bipartite.projected_graph(B, ["a", "b"], multigraph=True)
>>> print([sorted((u, v)) for u, v in [Link]()])
[['a', 'b'], ['a', 'b']]

Notes

No attempt is made to verify that the input graph B is bipartite. Returns a simple graph that is the projection of
the bipartite graph B onto the set of nodes given in list nodes. If multigraph=True then a multigraph is returned
with an edge for every shared neighbor.
Directed graphs are allowed as input. The output will also then be a directed graph with edges if there is a
directed path between the nodes.
The graph and node properties are (shallow) copied to the projected graph.
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
See also:
is_bipartite(), is_bipartite_node_set(), sets(), weighted_projected_graph(),
collaboration_weighted_projected_graph(), overlap_weighted_projected_graph(),
generic_weighted_projected_graph()

182 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

[Link].weighted_projected_graph

weighted_projected_graph(B, nodes, ratio=False)


Returns a weighted projection of B onto one of its node sets.
The weighted projected graph is the projection of the bipartite network B onto the specified nodes with weights
representing the number of shared neighbors or the ratio between actual shared neighbors and possible shared
neighbors if ratio is True1 . The nodes retain their attributes and are connected in the resulting graph if
they have an edge to a common node in the original graph.
Parameters
• B (NetworkX graph) – The input graph should be bipartite.
• nodes (list or iterable) – Nodes to project onto (the “bottom” nodes).
• ratio (Bool (default=False)) – If True, edge weight is the ratio between actual shared neigh-
bors and maximum possible shared neighbors (i.e., the size of the other node set). If False,
edges weight is the number of shared neighbors.
Returns Graph – A graph that is the projection onto the given nodes.
Return type NetworkX graph

Examples

>>> from [Link] import bipartite


>>> B = nx.path_graph(4)
>>> G = bipartite.weighted_projected_graph(B, [1, 3])
>>> list(G)
[1, 3]
>>> list([Link](data=True))
[(1, 3, {'weight': 1})]
>>> G = bipartite.weighted_projected_graph(B, [1, 3], ratio=True)
>>> list([Link](data=True))
[(1, 3, {'weight': 0.5})]

Notes

No attempt is made to verify that the input graph B is bipartite. The graph and node properties are (shallow)
copied to the projected graph.
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
See also:
is_bipartite(), is_bipartite_node_set(), sets(), collaboration_weighted_projected_graph(),
overlap_weighted_projected_graph(), generic_weighted_projected_graph(),
projected_graph()
1 Borgatti, S.P. and Halgin, D. In press. “Analyzing Affiliation Networks”. In Carrington, P. and Scott, J. (eds) The Sage Handbook of Social

Network Analysis. Sage Publications.

3.4. Bipartite 183


NetworkX Reference, Release 2.5

References

[Link].collaboration_weighted_projected_graph

collaboration_weighted_projected_graph(B, nodes)
Newman’s weighted projection of B onto one of its node sets.
The collaboration weighted projection is the projection of the bipartite network B onto the specified nodes with
weights assigned using Newman’s collaboration model1 :
∑︁ 𝛿 𝑘 𝛿 𝑘
𝑢 𝑣
𝑤𝑢,𝑣 =
𝑑𝑘 − 1
𝑘

where u and v are nodes from the bottom bipartite node set, and k is a node of the top node set. The value d_k
is the degree of node k in the bipartite network and delta_{u}^{k} is 1 if node u is linked to node k in the
original bipartite graph or 0 otherwise.
The nodes retain their attributes and are connected in the resulting graph if have an edge to a common node in
the original bipartite graph.
Parameters
• B (NetworkX graph) – The input graph should be bipartite.
• nodes (list or iterable) – Nodes to project onto (the “bottom” nodes).
Returns Graph – A graph that is the projection onto the given nodes.
Return type NetworkX graph

Examples

>>> from [Link] import bipartite


>>> B = nx.path_graph(5)
>>> B.add_edge(1, 5)
>>> G = bipartite.collaboration_weighted_projected_graph(B, [0, 2, 4, 5])
>>> list(G)
[0, 2, 4, 5]
>>> for edge in sorted([Link](data=True)):
... print(edge)
...
(0, 2, {'weight': 0.5})
(0, 5, {'weight': 0.5})
(2, 4, {'weight': 1.0})
(2, 5, {'weight': 0.5})

Notes

No attempt is made to verify that the input graph B is bipartite. The graph and node properties are (shallow)
copied to the projected graph.
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
See also:
1 Scientific collaboration networks: II. Shortest paths, weighted networks, and centrality, M. E. J. Newman, Phys. Rev. E 64, 016132 (2001).

184 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

is_bipartite(), is_bipartite_node_set(), sets(), weighted_projected_graph(),


overlap_weighted_projected_graph(), generic_weighted_projected_graph(),
projected_graph()

References

[Link].overlap_weighted_projected_graph

overlap_weighted_projected_graph(B, nodes, jaccard=True)


Overlap weighted projection of B onto one of its node sets.
The overlap weighted projection is the projection of the bipartite network B onto the specified nodes with
weights representing the Jaccard index between the neighborhoods of the two nodes in the original bipartite
network1 :
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑤𝑣,𝑢 =
|𝑁 (𝑢) ∪ 𝑁 (𝑣)|

or if the parameter ‘jaccard’ is False, the fraction of common neighbors by minimum of both nodes degree in
the original bipartite graph1 :

|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑤𝑣,𝑢 =
𝑚𝑖𝑛(|𝑁 (𝑢)|, |𝑁 (𝑣)|)

The nodes retain their attributes and are connected in the resulting graph if have an edge to a common node in
the original bipartite graph.
Parameters
• B (NetworkX graph) – The input graph should be bipartite.
• nodes (list or iterable) – Nodes to project onto (the “bottom” nodes).
• jaccard (Bool (default=True))
Returns Graph – A graph that is the projection onto the given nodes.
Return type NetworkX graph

Examples

>>> from [Link] import bipartite


>>> B = nx.path_graph(5)
>>> nodes = [0, 2, 4]
>>> G = bipartite.overlap_weighted_projected_graph(B, nodes)
>>> list(G)
[0, 2, 4]
>>> list([Link](data=True))
[(0, 2, {'weight': 0.5}), (2, 4, {'weight': 0.5})]
>>> G = bipartite.overlap_weighted_projected_graph(B, nodes, jaccard=False)
>>> list([Link](data=True))
[(0, 2, {'weight': 1.0}), (2, 4, {'weight': 1.0})]

1 Borgatti, S.P. and Halgin, D. In press. Analyzing Affiliation Networks. In Carrington, P. and Scott, J. (eds) The Sage Handbook of Social

Network Analysis. Sage Publications.

3.4. Bipartite 185


NetworkX Reference, Release 2.5

Notes

No attempt is made to verify that the input graph B is bipartite. The graph and node properties are (shallow)
copied to the projected graph.
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
See also:
is_bipartite(), is_bipartite_node_set(), sets(), weighted_projected_graph(),
collaboration_weighted_projected_graph(), generic_weighted_projected_graph(),
projected_graph()

References

[Link].generic_weighted_projected_graph

generic_weighted_projected_graph(B, nodes, weight_function=None)


Weighted projection of B with a user-specified weight function.
The bipartite network B is projected on to the specified nodes with weights computed by a user-specified func-
tion. This function must accept as a parameter the neighborhood sets of two nodes and return an integer or a
float.
The nodes retain their attributes and are connected in the resulting graph if they have an edge to a common node
in the original graph.
Parameters
• B (NetworkX graph) – The input graph should be bipartite.
• nodes (list or iterable) – Nodes to project onto (the “bottom” nodes).
• weight_function (function) – This function must accept as parameters the same input graph
that this function, and two nodes; and return an integer or a float. The default function
computes the number of shared neighbors.
Returns Graph – A graph that is the projection onto the given nodes.
Return type NetworkX graph

Examples

>>> from [Link] import bipartite


>>> # Define some custom weight functions
>>> def jaccard(G, u, v):
... unbrs = set(G[u])
... vnbrs = set(G[v])
... return float(len(unbrs & vnbrs)) / len(unbrs | vnbrs)
...
>>> def my_weight(G, u, v, weight="weight"):
... w = 0
... for nbr in set(G[u]) & set(G[v]):
... w += G[u][nbr].get(weight, 1) + G[v][nbr].get(weight, 1)
... return w
...
>>> # A complete bipartite graph with 4 nodes and 4 edges
>>> B = nx.complete_bipartite_graph(2, 2)
(continues on next page)

186 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

(continued from previous page)


>>> # Add some arbitrary weight to the edges
>>> for i, (u, v) in enumerate([Link]()):
... [Link][u, v]["weight"] = i + 1
...
>>> for edge in [Link](data=True):
... print(edge)
...
(0, 2, {'weight': 1})
(0, 3, {'weight': 2})
(1, 2, {'weight': 3})
(1, 3, {'weight': 4})
>>> # By default, the weight is the number of shared neighbors
>>> G = bipartite.generic_weighted_projected_graph(B, [0, 1])
>>> print(list([Link](data=True)))
[(0, 1, {'weight': 2})]
>>> # To specify a custom weight function use the weight_function parameter
>>> G = bipartite.generic_weighted_projected_graph(
... B, [0, 1], weight_function=jaccard
... )
>>> print(list([Link](data=True)))
[(0, 1, {'weight': 1.0})]
>>> G = bipartite.generic_weighted_projected_graph(
... B, [0, 1], weight_function=my_weight
... )
>>> print(list([Link](data=True)))
[(0, 1, {'weight': 10})]

Notes

No attempt is made to verify that the input graph B is bipartite. The graph and node properties are (shallow)
copied to the projected graph.
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
See also:
is_bipartite(), is_bipartite_node_set(), sets(), weighted_projected_graph(),
collaboration_weighted_projected_graph(), overlap_weighted_projected_graph(),
projected_graph()

3.4.6 Spectral

Spectral bipartivity measure.

spectral_bipartivity(G[, nodes, weight]) Returns the spectral bipartivity.

3.4. Bipartite 187


NetworkX Reference, Release 2.5

[Link].spectral_bipartivity

spectral_bipartivity(G, nodes=None, weight='weight')


Returns the spectral bipartivity.
Parameters
• G (NetworkX graph)
• nodes (list or container optional(default is all nodes)) – Nodes to return value of spectral
bipartivity contribution.
• weight (string or None optional (default = ‘weight’)) – Edge data key to use for edge
weights. If None, weights set to 1.
Returns sb – A single number if the keyword nodes is not specified, or a dictionary keyed by node
with the spectral bipartivity contribution of that node as the value.
Return type float or dict

Examples

>>> from [Link] import bipartite


>>> G = nx.path_graph(4)
>>> bipartite.spectral_bipartivity(G)
1.0

Notes

This implementation uses Numpy (dense) matrices which are not efficient for storing large sparse graphs.
See also:
color()

References

3.4.7 Clustering

Functions for computing clustering of pairs

clustering(G[, nodes, mode]) Compute a bipartite clustering coefficient for nodes.


average_clustering(G[, nodes, mode]) Compute the average bipartite clustering coefficient.
latapy_clustering(G[, nodes, mode]) Compute a bipartite clustering coefficient for nodes.
robins_alexander_clustering(G) Compute the bipartite clustering of G.

188 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

[Link]

clustering(G, nodes=None, mode='dot')


Compute a bipartite clustering coefficient for nodes.
The bipartie clustering coefficient is a measure of local density of connections defined as1 :
∑︀
𝑣∈𝑁 (𝑁 (𝑢)) 𝑐𝑢𝑣
𝑐𝑢 =
|𝑁 (𝑁 (𝑢))|

where N(N(u)) are the second order neighbors of u in G excluding u, and c_{uv} is the pairwise clustering
coefficient between nodes u and v.
The mode selects the function for c_{uv} which can be:
dot:
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑐𝑢𝑣 =
|𝑁 (𝑢) ∪ 𝑁 (𝑣)|
min:
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑐𝑢𝑣 =
𝑚𝑖𝑛(|𝑁 (𝑢)|, |𝑁 (𝑣)|)
max:
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑐𝑢𝑣 =
𝑚𝑎𝑥(|𝑁 (𝑢)|, |𝑁 (𝑣)|)

Parameters
• G (graph) – A bipartite graph
• nodes (list or iterable (optional)) – Compute bipartite clustering for these nodes. The default
is all nodes in G.
• mode (string) – The pariwise bipartite clustering method to be used in the computation. It
must be “dot”, “max”, or “min”.
Returns clustering – A dictionary keyed by node with the clustering coefficient value.
Return type dictionary

Examples

>>> from [Link] import bipartite


>>> G = nx.path_graph(4) # path graphs are bipartite
>>> c = [Link](G)
>>> c[0]
0.5
>>> c = [Link](G, mode="min")
>>> c[0]
1.0

See also:
robins_alexander_clustering(), square_clustering(), average_clustering()
1 Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008). Basic notions for the analysis of large two-mode networks. Social

Networks 30(1), 31–48.

3.4. Bipartite 189


NetworkX Reference, Release 2.5

References

[Link].average_clustering

average_clustering(G, nodes=None, mode='dot')


Compute the average bipartite clustering coefficient.
A clustering coefficient for the whole graph is the average,
1 ∑︁
𝐶= 𝑐𝑣 ,
𝑛
𝑣∈𝐺

where n is the number of nodes in G.


Similar measures for the two bipartite sets can be defined1
1 ∑︁
𝐶𝑋 = 𝑐𝑣 ,
|𝑋|
𝑣∈𝑋

where X is a bipartite set of G.


Parameters
• G (graph) – a bipartite graph
• nodes (list or iterable, optional) – A container of nodes to use in computing the average.
The nodes should be either the entire graph (the default) or one of the bipartite sets.
• mode (string) – The pariwise bipartite clustering method. It must be “dot”, “max”, or “min”
Returns clustering – The average bipartite clustering for the given set of nodes or the entire graph
if no nodes are specified.
Return type float

Examples

>>> from [Link] import bipartite


>>> G = nx.star_graph(3) # star graphs are bipartite
>>> bipartite.average_clustering(G)
0.75
>>> X, Y = [Link](G)
>>> bipartite.average_clustering(G, X)
0.0
>>> bipartite.average_clustering(G, Y)
1.0

See also:
clustering()
1Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008). Basic notions for the analysis of large two-mode networks. Social
Networks 30(1), 31–48.

190 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Notes

The container of nodes passed to this function must contain all of the nodes in one of the bipartite sets
(“top” or “bottom”) in order to compute the correct average bipartite clustering coefficients. See bipartite
documentation for further details on how bipartite graphs are handled in NetworkX.

References

[Link].latapy_clustering

latapy_clustering(G, nodes=None, mode='dot')


Compute a bipartite clustering coefficient for nodes.
The bipartie clustering coefficient is a measure of local density of connections defined as1 :
∑︀
𝑣∈𝑁 (𝑁 (𝑢)) 𝑐𝑢𝑣
𝑐𝑢 =
|𝑁 (𝑁 (𝑢))|

where N(N(u)) are the second order neighbors of u in G excluding u, and c_{uv} is the pairwise clustering
coefficient between nodes u and v.
The mode selects the function for c_{uv} which can be:
dot:
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑐𝑢𝑣 =
|𝑁 (𝑢) ∪ 𝑁 (𝑣)|
min:
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑐𝑢𝑣 =
𝑚𝑖𝑛(|𝑁 (𝑢)|, |𝑁 (𝑣)|)
max:
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑐𝑢𝑣 =
𝑚𝑎𝑥(|𝑁 (𝑢)|, |𝑁 (𝑣)|)

Parameters
• G (graph) – A bipartite graph
• nodes (list or iterable (optional)) – Compute bipartite clustering for these nodes. The default
is all nodes in G.
• mode (string) – The pariwise bipartite clustering method to be used in the computation. It
must be “dot”, “max”, or “min”.
Returns clustering – A dictionary keyed by node with the clustering coefficient value.
Return type dictionary
1 Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008). Basic notions for the analysis of large two-mode networks. Social

Networks 30(1), 31–48.

3.4. Bipartite 191


NetworkX Reference, Release 2.5

Examples

>>> from [Link] import bipartite


>>> G = nx.path_graph(4) # path graphs are bipartite
>>> c = [Link](G)
>>> c[0]
0.5
>>> c = [Link](G, mode="min")
>>> c[0]
1.0

See also:
robins_alexander_clustering(), square_clustering(), average_clustering()

References

[Link].robins_alexander_clustering

robins_alexander_clustering(G)
Compute the bipartite clustering of G.
Robins and Alexander1 defined bipartite clustering coefficient as four times the number of four cycles C_4
divided by the number of three paths L_3 in a bipartite graph:
4 * 𝐶4
𝐶𝐶4 =
𝐿3
Parameters G (graph) – a bipartite graph
Returns clustering – The Robins and Alexander bipartite clustering for the input graph.
Return type float

Examples

>>> from [Link] import bipartite


>>> G = nx.davis_southern_women_graph()
>>> print(round(bipartite.robins_alexander_clustering(G), 3))
0.468

See also:
latapy_clustering(), square_clustering()
1 Robins, G. and M. Alexander (2004). Small worlds among interlocking directors: Network structure and distance in bipartite graphs. Compu-
tational & Mathematical Organization Theory 10(1), 69–94.

192 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

References

3.4.8 Redundancy

Node redundancy for bipartite graphs.

node_redundancy(G[, nodes]) Computes the node redundancy coefficients for the


nodes in the bipartite graph G.

[Link].node_redundancy

node_redundancy(G, nodes=None)
Computes the node redundancy coefficients for the nodes in the bipartite graph G.
The redundancy coefficient of a node v is the fraction of pairs of neighbors of v that are both linked to other
nodes. In a one-mode projection these nodes would be linked together even if v were not there.
More formally, for any vertex v, the redundancy coefficient of `v` is defined by

|{{𝑢, 𝑤} ⊆ 𝑁 (𝑣), ∃𝑣 ′ ̸= 𝑣, (𝑣 ′ , 𝑢) ∈ 𝐸 and (𝑣 ′ , 𝑤) ∈ 𝐸}|


𝑟𝑐(𝑣) = |𝑁 (𝑣)|(|𝑁 (𝑣)|−1)
,
2

where N(v) is the set of neighbors of v in G.


Parameters
• G (graph) – A bipartite graph
• nodes (list or iterable (optional)) – Compute redundancy for these nodes. The default is all
nodes in G.
Returns redundancy – A dictionary keyed by node with the node redundancy value.
Return type dictionary

Examples

Compute the redundancy coefficient of each node in a graph:

>>> from [Link] import bipartite


>>> G = nx.cycle_graph(4)
>>> rc = bipartite.node_redundancy(G)
>>> rc[0]
1.0

Compute the average redundancy for the graph:

>>> from [Link] import bipartite


>>> G = nx.cycle_graph(4)
>>> rc = bipartite.node_redundancy(G)
>>> sum([Link]()) / len(G)
1.0

Compute the average redundancy for a set of nodes:

3.4. Bipartite 193


NetworkX Reference, Release 2.5

>>> from [Link] import bipartite


>>> G = nx.cycle_graph(4)
>>> rc = bipartite.node_redundancy(G)
>>> nodes = [0, 2]
>>> sum(rc[n] for n in nodes) / len(nodes)
1.0

Raises NetworkXError – If any of the nodes in the graph (or in nodes, if specified) has (out-
)degree less than two (which would result in division by zero, according to the definition of the
redundancy coefficient).

References

3.4.9 Centrality

closeness_centrality(G, nodes[, normalized]) Compute the closeness centrality for nodes in a bipartite
network.
degree_centrality(G, nodes) Compute the degree centrality for nodes in a bipartite
network.
betweenness_centrality(G, nodes) Compute betweenness centrality for nodes in a bipartite
network.

[Link].closeness_centrality

closeness_centrality(G, nodes, normalized=True)


Compute the closeness centrality for nodes in a bipartite network.
The closeness of a node is the distance to all other nodes in the graph or in the case that the graph is not connected
to all other nodes in the connected component containing that node.
Parameters
• G (graph) – A bipartite network
• nodes (list or container) – Container with all nodes in one bipartite node set.
• normalized (bool, optional) – If True (default) normalize by connected component size.
Returns closeness – Dictionary keyed by node with bipartite closeness centrality as the value.
Return type dictionary
See also:
betweenness_centrality(), degree_centrality(), sets(), is_bipartite()

194 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Notes

The nodes input parameter must contain all nodes in one bipartite node set, but the dictionary returned contains
all nodes from both node sets. See bipartite documentation for further details on how bipartite graphs
are handled in NetworkX.
Closeness centrality is normalized by the minimum distance possible. In the bipartite case the minimum distance
for a node in one bipartite node set is 1 from all nodes in the other node set and 2 from all other nodes in its own
set1 . Thus the closeness centrality for node v in the two bipartite sets U with n nodes and V with m nodes is

𝑚 + 2(𝑛 − 1)
𝑐𝑣 = , for𝑣 ∈ 𝑈,
𝑑
𝑛 + 2(𝑚 − 1)
𝑐𝑣 = , for𝑣 ∈ 𝑉,
𝑑
where d is the sum of the distances from v to all other nodes.
Higher values of closeness indicate higher centrality.
As in the unipartite case, setting normalized=True causes the values to normalized further to n-1 / size(G)-1
where n is the number of nodes in the connected part of graph containing the node. If the graph is not completely
connected, this algorithm computes the closeness centrality for each connected part separately.

References

[Link].degree_centrality

degree_centrality(G, nodes)
Compute the degree centrality for nodes in a bipartite network.
The degree centrality for a node v is the fraction of nodes connected to it.
Parameters
• G (graph) – A bipartite network
• nodes (list or container) – Container with all nodes in one bipartite node set.
Returns centrality – Dictionary keyed by node with bipartite degree centrality as the value.
Return type dictionary
See also:
betweenness_centrality(), closeness_centrality(), sets(), is_bipartite()

Notes

The nodes input parameter must contain all nodes in one bipartite node set, but the dictionary returned con-
tains all nodes from both bipartite node sets. See bipartite documentation for further details on how
bipartite graphs are handled in NetworkX.
For unipartite networks, the degree centrality values are normalized by dividing by the maximum possible degree
(which is n-1 where n is the number of nodes in G).
1 Borgatti, S.P. and Halgin, D. In press. “Analyzing Affiliation Networks”. In Carrington, P. and Scott, J. (eds) The Sage Handbook of Social

Network Analysis. Sage Publications. [Link]

3.4. Bipartite 195


NetworkX Reference, Release 2.5

In the bipartite case, the maximum possible degree of a node in a bipartite node set is the number of nodes in the
opposite node set1 . The degree centrality for a node v in the bipartite sets U with n nodes and V with m nodes is

𝑑𝑒𝑔(𝑣)
𝑑𝑣 = , for𝑣 ∈ 𝑈,
𝑚
𝑑𝑒𝑔(𝑣)
𝑑𝑣 = , for𝑣 ∈ 𝑉,
𝑛
where deg(v) is the degree of node v.

References

[Link].betweenness_centrality

betweenness_centrality(G, nodes)
Compute betweenness centrality for nodes in a bipartite network.
Betweenness centrality of a node v is the sum of the fraction of all-pairs shortest paths that pass through v.
Values of betweenness are normalized by the maximum possible value which for bipartite graphs is limited by
the relative size of the two node sets1 .
Let n be the number of nodes in the node set U and m be the number of nodes in the node set V, then nodes in U
are normalized by dividing by
1 2
[𝑚 (𝑠 + 1)2 + 𝑚(𝑠 + 1)(2𝑡 − 𝑠 − 1) − 𝑡(2𝑠 − 𝑡 + 3)],
2
where

𝑠 = (𝑛 − 1) ÷ 𝑚, 𝑡 = (𝑛 − 1) mod 𝑚,

and nodes in V are normalized by dividing by


1 2
[𝑛 (𝑝 + 1)2 + 𝑛(𝑝 + 1)(2𝑟 − 𝑝 − 1) − 𝑟(2𝑝 − 𝑟 + 3)],
2
where,

𝑝 = (𝑚 − 1) ÷ 𝑛, 𝑟 = (𝑚 − 1) mod 𝑛.

Parameters
• G (graph) – A bipartite graph
• nodes (list or container) – Container with all nodes in one bipartite node set.
Returns betweenness – Dictionary keyed by node with bipartite betweenness centrality as the value.
Return type dictionary
See also:
degree_centrality(), closeness_centrality(), sets(), is_bipartite()
1 Borgatti, S.P. and Halgin, D. In press. “Analyzing Affiliation Networks”. In Carrington, P. and Scott, J. (eds) The Sage Handbook of Social

Network Analysis. Sage Publications. [Link]


1 Borgatti, S.P. and Halgin, D. In press. “Analyzing Affiliation Networks”. In Carrington, P. and Scott, J. (eds) The Sage Handbook of Social

Network Analysis. Sage Publications. [Link]

196 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Notes

The nodes input parameter must contain all nodes in one bipartite node set, but the dictionary returned contains
all nodes from both node sets. See bipartite documentation for further details on how bipartite graphs
are handled in NetworkX.

References

3.4.10 Generators

Generators and functions for bipartite graphs.

complete_bipartite_graph(n1, n2[, cre- Returns the complete bipartite graph K_{n_1,n_2}.


ate_using])
configuration_model(aseq, bseq[, . . . ]) Returns a random bipartite graph from two given degree
sequences.
havel_hakimi_graph(aseq, bseq[, create_using]) Returns a bipartite graph from two given degree se-
quences using a Havel-Hakimi style construction.
reverse_havel_hakimi_graph(aseq, bseq[, Returns a bipartite graph from two given degree se-
. . . ]) quences using a Havel-Hakimi style construction.
alternating_havel_hakimi_graph(aseq, Returns a bipartite graph from two given degree se-
bseq[, . . . ]) quences using an alternating Havel-Hakimi style con-
struction.
preferential_attachment_graph(aseq, p[, Create a bipartite graph with a preferential attachment
. . . ]) model from a given single degree sequence.
random_graph(n, m, p[, seed, directed]) Returns a bipartite random graph.
gnmk_random_graph(n, m, k[, seed, directed]) Returns a random bipartite graph G_{n,m,k}.

[Link].complete_bipartite_graph

complete_bipartite_graph(n1, n2, create_using=None)


Returns the complete bipartite graph K_{n_1,n_2}.
The graph is composed of two partitions with nodes 0 to (n1 - 1) in the first and nodes n1 to (n1 + n2 - 1) in the
second. Each node in the first is connected to each node in the second.
Parameters
• n1 (integer) – Number of nodes for node set A.
• n2 (integer) – Number of nodes for node set B.
• create_using (NetworkX graph instance, optional) – Return graph of this type.

3.4. Bipartite 197


NetworkX Reference, Release 2.5

Notes

Node labels are the integers 0 to n_1 + n_2 - 1.


The nodes are assigned the attribute ‘bipartite’ with the value 0 or 1 to indicate which bipartite set the node
belongs to.
This function is not imported in the main namespace. To use it use [Link].complete_bipartite_graph

[Link].configuration_model

configuration_model(aseq, bseq, create_using=None, seed=None)


Returns a random bipartite graph from two given degree sequences.
Parameters
• aseq (list) – Degree sequence for node set A.
• bseq (list) – Degree sequence for node set B.
• create_using (NetworkX graph instance, optional) – Return graph of this type.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
• The graph is composed of two partitions. Set A has nodes 0 to
• (len(aseq) - 1) and set B has nodes len(aseq) to (len(bseq) - 1).
• Nodes from set A are connected to nodes in set B by choosing
• randomly from the possible free stubs, one in A and one in B.

Notes

The sum of the two sequences must be equal: sum(aseq)=sum(bseq) If no graph type is specified use MultiGraph
with parallel edges. If you want a graph with no parallel edges use create_using=Graph() but then the resulting
degree sequences might not be exact.
The nodes are assigned the attribute ‘bipartite’ with the value 0 or 1 to indicate which bipartite set the node
belongs to.
This function is not imported in the main namespace. To use it use [Link].configuration_model

[Link].havel_hakimi_graph

havel_hakimi_graph(aseq, bseq, create_using=None)


Returns a bipartite graph from two given degree sequences using a Havel-Hakimi style construction.
The graph is composed of two partitions. Set A has nodes 0 to (len(aseq) - 1) and set B has nodes len(aseq) to
(len(bseq) - 1). Nodes from the set A are connected to nodes in the set B by connecting the highest degree nodes
in set A to the highest degree nodes in set B until all stubs are connected.
Parameters
• aseq (list) – Degree sequence for node set A.
• bseq (list) – Degree sequence for node set B.
• create_using (NetworkX graph instance, optional) – Return graph of this type.

198 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Notes

The sum of the two sequences must be equal: sum(aseq)=sum(bseq) If no graph type is specified use MultiGraph
with parallel edges. If you want a graph with no parallel edges use create_using=Graph() but then the resulting
degree sequences might not be exact.
The nodes are assigned the attribute ‘bipartite’ with the value 0 or 1 to indicate which bipartite set the node
belongs to.
This function is not imported in the main namespace. To use it use [Link].havel_hakimi_graph

[Link].reverse_havel_hakimi_graph

reverse_havel_hakimi_graph(aseq, bseq, create_using=None)


Returns a bipartite graph from two given degree sequences using a Havel-Hakimi style construction.
The graph is composed of two partitions. Set A has nodes 0 to (len(aseq) - 1) and set B has nodes len(aseq) to
(len(bseq) - 1). Nodes from set A are connected to nodes in the set B by connecting the highest degree nodes in
set A to the lowest degree nodes in set B until all stubs are connected.
Parameters
• aseq (list) – Degree sequence for node set A.
• bseq (list) – Degree sequence for node set B.
• create_using (NetworkX graph instance, optional) – Return graph of this type.

Notes

The sum of the two sequences must be equal: sum(aseq)=sum(bseq) If no graph type is specified use MultiGraph
with parallel edges. If you want a graph with no parallel edges use create_using=Graph() but then the resulting
degree sequences might not be exact.
The nodes are assigned the attribute ‘bipartite’ with the value 0 or 1 to indicate which bipartite set the node
belongs to.
This function is not imported in the main namespace. To use it use [Link].reverse_havel_hakimi_graph

[Link].alternating_havel_hakimi_graph

alternating_havel_hakimi_graph(aseq, bseq, create_using=None)


Returns a bipartite graph from two given degree sequences using an alternating Havel-Hakimi style construction.
The graph is composed of two partitions. Set A has nodes 0 to (len(aseq) - 1) and set B has nodes len(aseq) to
(len(bseq) - 1). Nodes from the set A are connected to nodes in the set B by connecting the highest degree nodes
in set A to alternatively the highest and the lowest degree nodes in set B until all stubs are connected.
Parameters
• aseq (list) – Degree sequence for node set A.
• bseq (list) – Degree sequence for node set B.
• create_using (NetworkX graph instance, optional) – Return graph of this type.

3.4. Bipartite 199


NetworkX Reference, Release 2.5

Notes

The sum of the two sequences must be equal: sum(aseq)=sum(bseq) If no graph type is specified use MultiGraph
with parallel edges. If you want a graph with no parallel edges use create_using=Graph() but then the resulting
degree sequences might not be exact.
The nodes are assigned the attribute ‘bipartite’ with the value 0 or 1 to indicate which bipartite set the node
belongs to.
This function is not imported in the main namespace. To use it use [Link].alternating_havel_hakimi_graph

[Link].preferential_attachment_graph

preferential_attachment_graph(aseq, p, create_using=None, seed=None)


Create a bipartite graph with a preferential attachment model from a given single degree sequence.
The graph is composed of two partitions. Set A has nodes 0 to (len(aseq) - 1) and set B has nodes starting with
node len(aseq). The number of nodes in set B is random.
Parameters
• aseq (list) – Degree sequence for node set A.
• p (float) – Probability that a new bottom node is added.
• create_using (NetworkX graph instance, optional) – Return graph of this type.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.

References

Notes

The nodes are assigned the attribute ‘bipartite’ with the value 0 or 1 to indicate which bipartite set the node
belongs to.
This function is not imported in the main namespace. To use it use [Link].preferential_attachment_graph

[Link].random_graph

random_graph(n, m, p, seed=None, directed=False)


Returns a bipartite random graph.
This is a bipartite version of the binomial (Erdős-Rényi) graph. The graph is composed of two partitions. Set A
has nodes 0 to (n - 1) and set B has nodes n to (n + m - 1).
Parameters
• n (int) – The number of nodes in the first bipartite set.
• m (int) – The number of nodes in the second bipartite set.
• p (float) – Probability for edge creation.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
• directed (bool, optional (default=False)) – If True return a directed graph

200 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Notes

The bipartite random graph algorithm chooses each of the n*m (undirected) or 2*nm (directed) possible edges
with probability p.
This algorithm is 𝑂(𝑛 + 𝑚) where 𝑚 is the expected number of edges.
The nodes are assigned the attribute ‘bipartite’ with the value 0 or 1 to indicate which bipartite set the node
belongs to.
This function is not imported in the main namespace. To use it use [Link].random_graph
See also:
gnp_random_graph(), configuration_model()

References

[Link].gnmk_random_graph

gnmk_random_graph(n, m, k, seed=None, directed=False)


Returns a random bipartite graph G_{n,m,k}.
Produces a bipartite graph chosen randomly out of the set of all graphs with n top nodes, m bottom nodes, and
k edges. The graph is composed of two sets of nodes. Set A has nodes 0 to (n - 1) and set B has nodes n to (n +
m - 1).
Parameters
• n (int) – The number of nodes in the first bipartite set.
• m (int) – The number of nodes in the second bipartite set.
• k (int) – The number of edges
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
• directed (bool, optional (default=False)) – If True return a directed graph

Examples

from [Link] import bipartite G = bipartite.gnmk_random_graph(10,20,50)


See also:
gnm_random_graph()

Notes

If k > m * n then a complete bipartite graph is returned.


This graph is a bipartite version of the G_{nm} random graph model.
The nodes are assigned the attribute ‘bipartite’ with the value 0 or 1 to indicate which bipartite set the node
belongs to.
This function is not imported in the main namespace. To use it use [Link].gnmk_random_graph

3.4. Bipartite 201


NetworkX Reference, Release 2.5

3.4.11 Covering

Functions related to graph covers.

min_edge_cover(G[, matching_algorithm]) Returns a set of edges which constitutes the minimum


edge cover of the graph.

[Link].min_edge_cover

min_edge_cover(G, matching_algorithm=None)
Returns a set of edges which constitutes the minimum edge cover of the graph.
The smallest edge cover can be found in polynomial time by finding a maximum matching and extending it
greedily so that all nodes are covered.
Parameters
• G (NetworkX graph) – An undirected bipartite graph.
• matching_algorithm (function) – A function that returns a maximum cardinality matching
in a given bipartite graph. The function must take one input, the graph G, and return a dic-
tionary mapping each node to its mate. If not specified, hopcroft_karp_matching()
will be used. Other possibilities include eppstein_matching(),
Returns A set of the edges in a minimum edge cover of the graph, given as pairs of nodes. It contains
both the edges (u, v) and (v, u) for given nodes u and v among the edges of minimum
edge cover.
Return type set

Notes

An edge cover of a graph is a set of edges such that every node of the graph is incident to at least one edge of
the set. A minimum edge cover is an edge covering of smallest cardinality.
Due to its implementation, the worst-case running time of this algorithm is bounded by the worst-case running
time of the function matching_algorithm.

3.5 Boundary

Routines to find the boundary of a set of nodes.


An edge boundary is a set of edges, each of which has exactly one endpoint in a given set of nodes (or, in the case of
directed graphs, the set of edges whose source node is in the set).
A node boundary of a set S of nodes is the set of (out-)neighbors of nodes in S that are outside S.

edge_boundary(G, nbunch1[, nbunch2, data, . . . ]) Returns the edge boundary of nbunch1.


node_boundary(G, nbunch1[, nbunch2]) Returns the node boundary of nbunch1.

202 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

3.5.1 [Link].edge_boundary

edge_boundary(G, nbunch1, nbunch2=None, data=False, keys=False, default=None)


Returns the edge boundary of nbunch1.
The edge boundary of a set S with respect to a set T is the set of edges (u, v) such that u is in S and v is in T. If
T is not specified, it is assumed to be the set of all nodes not in S.
Parameters
• G (NetworkX graph)
• nbunch1 (iterable) – Iterable of nodes in the graph representing the set of nodes whose edge
boundary will be returned. (This is the set S from the definition above.)
• nbunch2 (iterable) – Iterable of nodes representing the target (or “exterior”) set of nodes.
(This is the set T from the definition above.) If not specified, this is assumed to be the set of
all nodes in G not in nbunch1.
• keys (bool) – This parameter has the same meaning as in [Link]().
• data (bool or object) – This parameter has the same meaning as in MultiGraph.
edges().
• default (object) – This parameter has the same meaning as in [Link]().
Returns An iterator over the edges in the boundary of nbunch1 with respect to nbunch2. If
keys, data, or default are specified and G is a multigraph, then edges are returned with
keys and/or data, as in [Link]().
Return type iterator

Notes

Any element of nbunch that is not in the graph G will be ignored.


nbunch1 and nbunch2 are usually meant to be disjoint, but in the interest of speed and generality, that is not
required here.

3.5.2 [Link].node_boundary

node_boundary(G, nbunch1, nbunch2=None)


Returns the node boundary of nbunch1.
The node boundary of a set S with respect to a set T is the set of nodes v in T such that for some u in S, there is
an edge joining u to v. If T is not specified, it is assumed to be the set of all nodes not in S.
Parameters
• G (NetworkX graph)
• nbunch1 (iterable) – Iterable of nodes in the graph representing the set of nodes whose node
boundary will be returned. (This is the set S from the definition above.)
• nbunch2 (iterable) – Iterable of nodes representing the target (or “exterior”) set of nodes.
(This is the set T from the definition above.) If not specified, this is assumed to be the set of
all nodes in G not in nbunch1.
Returns The node boundary of nbunch1 with respect to nbunch2.
Return type set

3.5. Boundary 203


NetworkX Reference, Release 2.5

Notes

Any element of nbunch that is not in the graph G will be ignored.


nbunch1 and nbunch2 are usually meant to be disjoint, but in the interest of speed and generality, that is not
required here.

3.6 Bridges

Bridge-finding algorithms.

bridges(G[, root]) Generate all bridges in a graph.


has_bridges(G[, root]) Decide whether a graph has any bridges.
local_bridges(G[, with_span, weight]) Iterate over local bridges of G optionally computing the
span

3.6.1 [Link]

bridges(G, root=None)
Generate all bridges in a graph.
A bridge in a graph is an edge whose removal causes the number of connected components of the graph to
increase. Equivalently, a bridge is an edge that does not belong to any cycle.
Parameters
• G (undirected graph)
• root (node (optional)) – A node in the graph G. If specified, only the bridges in the connected
component containing this node will be returned.
Yields e (edge) – An edge in the graph whose removal disconnects the graph (or causes the number
of connected components to increase).
Raises NodeNotFound – If root is not in the graph G.

Examples

The barbell graph with parameter zero has a single bridge:

>>> G = nx.barbell_graph(10, 0)
>>> list([Link](G))
[(9, 10)]

204 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Notes

This is an implementation of the algorithm described in _[1]. An edge is a bridge if and only if it is not contained
in any chain. Chains are found using the networkx.chain_decomposition() function.
Ignoring polylogarithmic factors, the worst-case time complexity is the same as the networkx.
chain_decomposition() function, 𝑂(𝑚 + 𝑛), where 𝑛 is the number of nodes in the graph and 𝑚 is
the number of edges.

References

3.6.2 [Link].has_bridges

has_bridges(G, root=None)
Decide whether a graph has any bridges.
A bridge in a graph is an edge whose removal causes the number of connected components of the graph to
increase.
Parameters
• G (undirected graph)
• root (node (optional)) – A node in the graph G. If specified, only the bridges in the connected
component containing this node will be considered.
Returns Whether the graph (or the connected component containing root) has any bridges.
Return type bool
Raises NodeNotFound – If root is not in the graph G.

Examples

The barbell graph with parameter zero has a single bridge:

>>> G = nx.barbell_graph(10, 0)
>>> nx.has_bridges(G)
True

On the other hand, the cycle graph has no bridges:

>>> G = nx.cycle_graph(5)
>>> nx.has_bridges(G)
False

Notes

This implementation uses the [Link]() function, so it shares its worst-case time complexity,
𝑂(𝑚 + 𝑛), ignoring polylogarithmic factors, where 𝑛 is the number of nodes in the graph and 𝑚 is the number
of edges.

3.6. Bridges 205


NetworkX Reference, Release 2.5

3.6.3 [Link].local_bridges

local_bridges(G, with_span=True, weight=None)


Iterate over local bridges of G optionally computing the span
A local bridge is an edge whose endpoints have no common neighbors. That is, the edge is not part of a triangle
in the graph.
The span of a local bridge is the shortest path length between the endpoints if the local bridge is removed.
Parameters
• G (undirected graph)
• with_span (bool) – If True, yield a 3-tuple (u, v, span)
• weight (function, string or None (default: None)) – If function, used to compute edge
weights for the span. If string, the edge data attribute used in calculating span. If None,
all edges have weight 1.
Yields e (edge) – The local bridges as an edge 2-tuple of nodes (u, v) or as a 3-tuple (u, v,
span) when with_span is True.

Examples

A cycle graph has every edge a local bridge with span N-1.

>>> G = nx.cycle_graph(9)
>>> (0, 8, 8) in set(nx.local_bridges(G))
True

3.7 Centrality

3.7.1 Degree

degree_centrality(G) Compute the degree centrality for nodes.


in_degree_centrality(G) Compute the in-degree centrality for nodes.
out_degree_centrality(G) Compute the out-degree centrality for nodes.

[Link].degree_centrality

degree_centrality(G)
Compute the degree centrality for nodes.
The degree centrality for a node v is the fraction of nodes it is connected to.
Parameters G (graph) – A networkx graph
Returns nodes – Dictionary of nodes with degree centrality as the value.
Return type dictionary
See also:
betweenness_centrality(), load_centrality(), eigenvector_centrality()

206 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Notes

The degree centrality values are normalized by dividing by the maximum possible degree in a simple graph n-1
where n is the number of nodes in G.
For multigraphs or graphs with self loops the maximum degree might be higher than n-1 and values of degree
centrality greater than 1 are possible.

[Link].in_degree_centrality

in_degree_centrality(G)
Compute the in-degree centrality for nodes.
The in-degree centrality for a node v is the fraction of nodes its incoming edges are connected to.
Parameters G (graph) – A NetworkX graph
Returns nodes – Dictionary of nodes with in-degree centrality as values.
Return type dictionary
Raises NetworkXNotImplemented – If G is undirected.
See also:
degree_centrality(), out_degree_centrality()

Notes

The degree centrality values are normalized by dividing by the maximum possible degree in a simple graph n-1
where n is the number of nodes in G.
For multigraphs or graphs with self loops the maximum degree might be higher than n-1 and values of degree
centrality greater than 1 are possible.

[Link].out_degree_centrality

out_degree_centrality(G)
Compute the out-degree centrality for nodes.
The out-degree centrality for a node v is the fraction of nodes its outgoing edges are connected to.
Parameters G (graph) – A NetworkX graph
Returns nodes – Dictionary of nodes with out-degree centrality as values.
Return type dictionary
Raises NetworkXNotImplemented – If G is undirected.
See also:
degree_centrality(), in_degree_centrality()

3.7. Centrality 207


NetworkX Reference, Release 2.5

Notes

The degree centrality values are normalized by dividing by the maximum possible degree in a simple graph n-1
where n is the number of nodes in G.
For multigraphs or graphs with self loops the maximum degree might be higher than n-1 and values of degree
centrality greater than 1 are possible.

3.7.2 Eigenvector

eigenvector_centrality(G[, max_iter, tol, Compute the eigenvector centrality for the graph G.
. . . ])
eigenvector_centrality_numpy(G[, weight, Compute the eigenvector centrality for the graph G.
. . . ])
katz_centrality(G[, alpha, beta, max_iter, . . . ]) Compute the Katz centrality for the nodes of the graph
G.
katz_centrality_numpy(G[, alpha, beta, . . . ]) Compute the Katz centrality for the graph G.

[Link].eigenvector_centrality

eigenvector_centrality(G, max_iter=100, tol=1e-06, nstart=None, weight=None)


Compute the eigenvector centrality for the graph G.
Eigenvector centrality computes the centrality for a node based on the centrality of its neighbors. The eigenvec-
tor centrality for node 𝑖 is the 𝑖-th element of the vector 𝑥 defined by the equation

𝐴𝑥 = 𝜆𝑥

where 𝐴 is the adjacency matrix of the graph G with eigenvalue 𝜆. By virtue of the Perron–Frobenius theorem,
there is a unique solution 𝑥, all of whose entries are positive, if 𝜆 is the largest eigenvalue of the adjacency
matrix 𝐴 (2 ).
Parameters
• G (graph) – A networkx graph
• max_iter (integer, optional (default=100)) – Maximum number of iterations in power
method.
• tol (float, optional (default=1.0e-6)) – Error tolerance used to check convergence in power
method iteration.
• nstart (dictionary, optional (default=None)) – Starting value of eigenvector iteration for
each node.
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
Returns nodes – Dictionary of nodes with eigenvector centrality as the value.
Return type dictionary
2 Mark E. J. Newman. Networks: An Introduction. Oxford University Press, USA, 2010, pp. 169.

208 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Examples

>>> G = nx.path_graph(4)
>>> centrality = nx.eigenvector_centrality(G)
>>> sorted((v, f"{c:0.2f}") for v, c in [Link]())
[(0, '0.37'), (1, '0.60'), (2, '0.60'), (3, '0.37')]

Raises
• NetworkXPointlessConcept – If the graph G is the null graph.
• NetworkXError – If each value in nstart is zero.
• PowerIterationFailedConvergence – If the algorithm fails to converge to the
specified tolerance within the specified number of iterations of the power iteration method.

See also:
eigenvector_centrality_numpy(), pagerank(), hits()

Notes

The measure was introduced by1 and is discussed in2 .


The power iteration method is used to compute the eigenvector and convergence is not guaranteed. Our method
stops after max_iter iterations or when the change in the computed vector between two iterations is smaller
than an error tolerance of G.number_of_nodes() * tol. This implementation uses (𝐴 + 𝐼) rather than
the adjacency matrix 𝐴 because it shifts the spectrum to enable discerning the correct eigenvector even for
networks with multiple dominant eigenvalues.
For directed graphs this is “left” eigenvector centrality which corresponds to the in-edges in the graph. For
out-edges eigenvector centrality first reverse the graph with [Link]().

References

[Link].eigenvector_centrality_numpy

eigenvector_centrality_numpy(G, weight=None, max_iter=50, tol=0)


Compute the eigenvector centrality for the graph G.
Eigenvector centrality computes the centrality for a node based on the centrality of its neighbors. The eigenvec-
tor centrality for node 𝑖 is

𝐴𝑥 = 𝜆𝑥

where 𝐴 is the adjacency matrix of the graph G with eigenvalue 𝜆. By virtue of the Perron–Frobenius theorem,
there is a unique and positive solution if 𝜆 is the largest eigenvalue associated with the eigenvector of the
adjacency matrix 𝐴 (2 ).
Parameters
• G (graph) – A networkx graph
1 Phillip Bonacich. “Power and Centrality: A Family of Measures.” American Journal of Sociology 92(5):1170–1182, 1986 <[Link]
[Link]/hse/2014/socialnetworks/papers/[Link]>
2 Mark E. J. Newman: Networks: An Introduction. Oxford University Press, USA, 2010, pp. 169.

3.7. Centrality 209


NetworkX Reference, Release 2.5

• weight (None or string, optional (default=None)) – The name of the edge attribute used as
weight. If None, all edge weights are considered equal.
• max_iter (integer, optional (default=100)) – Maximum number of iterations in power
method.
• tol (float, optional (default=1.0e-6)) – Relative accuracy for eigenvalues (stopping crite-
rion). The default value of 0 implies machine precision.
Returns nodes – Dictionary of nodes with eigenvector centrality as the value.
Return type dictionary

Examples

>>> G = nx.path_graph(4)
>>> centrality = nx.eigenvector_centrality_numpy(G)
>>> print([f"{node} {centrality[node]:0.2f}" for node in centrality])
['0 0.37', '1 0.60', '2 0.60', '3 0.37']

See also:
eigenvector_centrality(), pagerank(), hits()

Notes

The measure was introduced by1 .


This algorithm uses the SciPy sparse eigenvalue solver (ARPACK) to find the largest eigenvalue/eigenvector
pair.
For directed graphs this is “left” eigenvector centrality which corresponds to the in-edges in the graph. For
out-edges eigenvector centrality first reverse the graph with [Link]().
Raises NetworkXPointlessConcept – If the graph G is the null graph.

References

[Link].katz_centrality

katz_centrality(G, alpha=0.1, beta=1.0, max_iter=1000, tol=1e-06, nstart=None, normalized=True,


weight=None)
Compute the Katz centrality for the nodes of the graph G.
Katz centrality computes the centrality for a node based on the centrality of its neighbors. It is a generalization
of the eigenvector centrality. The Katz centrality for node 𝑖 is
∑︁
𝑥𝑖 = 𝛼 𝐴𝑖𝑗 𝑥𝑗 + 𝛽,
𝑗

where 𝐴 is the adjacency matrix of graph G with eigenvalues 𝜆.


The parameter 𝛽 controls the initial centrality and
1
𝛼< .
𝜆max
1 Phillip Bonacich: Power and Centrality: A Family of Measures. American Journal of Sociology 92(5):1170–1182, 1986 [Link]
[Link]/hse/2014/socialnetworks/papers/[Link]

210 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Katz centrality computes the relative influence of a node within a network by measuring the number of the
immediate neighbors (first degree nodes) and also all other nodes in the network that connect to the node under
consideration through these immediate neighbors.
Extra weight can be provided to immediate neighbors through the parameter 𝛽. Connections made with distant
neighbors are, however, penalized by an attenuation factor 𝛼 which should be strictly less than the inverse largest
eigenvalue of the adjacency matrix in order for the Katz centrality to be computed correctly. More information
is provided in1 .
Parameters
• G (graph) – A NetworkX graph.
• alpha (float) – Attenuation factor
• beta (scalar or dictionary, optional (default=1.0)) – Weight attributed to the immediate
neighborhood. If not a scalar, the dictionary must have an value for every node.
• max_iter (integer, optional (default=1000)) – Maximum number of iterations in power
method.
• tol (float, optional (default=1.0e-6)) – Error tolerance used to check convergence in power
method iteration.
• nstart (dictionary, optional) – Starting value of Katz iteration for each node.
• normalized (bool, optional (default=True)) – If True normalize the resulting values.
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
Returns nodes – Dictionary of nodes with Katz centrality as the value.
Return type dictionary
Raises
• NetworkXError – If the parameter beta is not a scalar but lacks a value for at least one
node
• PowerIterationFailedConvergence – If the algorithm fails to converge to the
specified tolerance within the specified number of iterations of the power iteration method.

Examples

>>> import math


>>> G = nx.path_graph(4)
>>> phi = (1 + [Link](5)) / 2.0 # largest eigenvalue of adj matrix
>>> centrality = nx.katz_centrality(G, 1 / phi - 0.01)
>>> for n, c in sorted([Link]()):
... print(f"{n} {c:.2f}")
0 0.37
1 0.60
2 0.60
3 0.37

See also:
katz_centrality_numpy(), eigenvector_centrality(), eigenvector_centrality_numpy(),
pagerank(), hits()
1 Mark E. J. Newman: Networks: An Introduction. Oxford University Press, USA, 2010, p. 720.

3.7. Centrality 211


NetworkX Reference, Release 2.5

Notes

Katz centrality was introduced by2 .


This algorithm it uses the power method to find the eigenvector corresponding to the largest eigenvalue of the
adjacency matrix of G. The parameter alpha should be strictly less than the inverse of largest eigenvalue of the
adjacency matrix for the algorithm to converge. You can use max(nx.adjacency_spectrum(G)) to get
𝜆max the largest eigenvalue of the adjacency matrix. The iteration will stop after max_iter iterations or an
error tolerance of number_of_nodes(G) * tol has been reached.
When 𝛼 = 1/𝜆max and 𝛽 = 0, Katz centrality is the same as eigenvector centrality.
For directed graphs this finds “left” eigenvectors which corresponds to the in-edges in the graph. For out-edges
Katz centrality first reverse the graph with [Link]().

References

[Link].katz_centrality_numpy

katz_centrality_numpy(G, alpha=0.1, beta=1.0, normalized=True, weight=None)


Compute the Katz centrality for the graph G.
Katz centrality computes the centrality for a node based on the centrality of its neighbors. It is a generalization
of the eigenvector centrality. The Katz centrality for node 𝑖 is
∑︁
𝑥𝑖 = 𝛼 𝐴𝑖𝑗 𝑥𝑗 + 𝛽,
𝑗

where 𝐴 is the adjacency matrix of graph G with eigenvalues 𝜆.


The parameter 𝛽 controls the initial centrality and
1
𝛼< .
𝜆max
Katz centrality computes the relative influence of a node within a network by measuring the number of the
immediate neighbors (first degree nodes) and also all other nodes in the network that connect to the node under
consideration through these immediate neighbors.
Extra weight can be provided to immediate neighbors through the parameter 𝛽. Connections made with distant
neighbors are, however, penalized by an attenuation factor 𝛼 which should be strictly less than the inverse largest
eigenvalue of the adjacency matrix in order for the Katz centrality to be computed correctly. More information
is provided in1 .
Parameters
• G (graph) – A NetworkX graph
• alpha (float) – Attenuation factor
• beta (scalar or dictionary, optional (default=1.0)) – Weight attributed to the immediate
neighborhood. If not a scalar the dictionary must have an value for every node.
• normalized (bool) – If True normalize the resulting values.
• weight (None or string, optional) – If None, all edge weights are considered equal. Other-
wise holds the name of the edge attribute used as weight.
2 Leo Katz: A New Status Index Derived from Sociometric Index. Psychometrika 18(1):39–43, 1953 [Link]
[Link]
1 Mark E. J. Newman: Networks: An Introduction. Oxford University Press, USA, 2010, p. 720.

212 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Returns nodes – Dictionary of nodes with Katz centrality as the value.


Return type dictionary
Raises NetworkXError – If the parameter beta is not a scalar but lacks a value for at least one
node

Examples

>>> import math


>>> G = nx.path_graph(4)
>>> phi = (1 + [Link](5)) / 2.0 # largest eigenvalue of adj matrix
>>> centrality = nx.katz_centrality_numpy(G, 1 / phi)
>>> for n, c in sorted([Link]()):
... print(f"{n} {c:.2f}")
0 0.37
1 0.60
2 0.60
3 0.37

See also:
katz_centrality(), eigenvector_centrality_numpy(), eigenvector_centrality(),
pagerank(), hits()

Notes

Katz centrality was introduced by2 .


This algorithm uses a direct linear solver to solve the above equation. The parameter alpha should be strictly
less than the inverse of largest eigenvalue of the adjacency matrix for there to be a solution. You can use
max(nx.adjacency_spectrum(G)) to get 𝜆max the largest eigenvalue of the adjacency matrix.
When 𝛼 = 1/𝜆max and 𝛽 = 0, Katz centrality is the same as eigenvector centrality.
For directed graphs this finds “left” eigenvectors which corresponds to the in-edges in the graph. For out-edges
Katz centrality first reverse the graph with [Link]().

References

3.7.3 Closeness

closeness_centrality(G[, u, distance, . . . ]) Compute closeness centrality for nodes.


incremental_closeness_centrality(G, Incremental closeness centrality for nodes.
edge[, . . . ])
2Leo Katz: A New Status Index Derived from Sociometric Index. Psychometrika 18(1):39–43, 1953 [Link]
[Link]

3.7. Centrality 213


NetworkX Reference, Release 2.5

[Link].closeness_centrality

closeness_centrality(G, u=None, distance=None, wf_improved=True)


Compute closeness centrality for nodes.
Closeness centrality1 of a node u is the reciprocal of the average shortest path distance to u over all n-1
reachable nodes.
𝑛−1
𝐶(𝑢) = ∑︀𝑛−1 ,
𝑣=1 𝑑(𝑣, 𝑢)

where d(v, u) is the shortest-path distance between v and u, and n is the number of nodes that can reach
u. Notice that the closeness distance function computes the incoming distance to u for directed graphs. To use
outward distance, act on [Link]().
Notice that higher values of closeness indicate higher centrality.
Wasserman and Faust propose an improved formula for graphs with more than one connected component. The
result is “a ratio of the fraction of actors in the group who are reachable, to the average distance” from the
reachable actors2 . You might think this scale factor is inverted but it is not. As is, nodes from small components
receive a smaller closeness value. Letting N denote the number of nodes in the graph,
𝑛−1 𝑛−1
𝐶𝑊 𝐹 (𝑢) = ,
𝑁 − 1 𝑛−1
∑︀
𝑣=1 𝑑(𝑣, 𝑢)

Parameters
• G (graph) – A NetworkX graph
• u (node, optional) – Return only the value for node u
• distance (edge attribute key, optional (default=None)) – Use the specified edge attribute as
the edge distance in shortest path calculations
• wf_improved (bool, optional (default=True)) – If True, scale by the fraction of nodes reach-
able. This gives the Wasserman and Faust improved formula. For single component graphs
it is the same as the original formula.
Returns nodes – Dictionary of nodes with closeness centrality as the value.
Return type dictionary
See also:
betweenness_centrality(), load_centrality(), eigenvector_centrality(),
degree_centrality(), incremental_closeness_centrality()

Notes

The closeness centrality is normalized to (n-1)/(|G|-1) where n is the number of nodes in the connected
part of graph containing the node. If the graph is not completely connected, this algorithm computes the close-
ness centrality for each connected part separately scaled by that parts size.
If the ‘distance’ keyword is set to an edge attribute key then the shortest-path length will be computed using
Dijkstra’s algorithm with that edge attribute as the edge weight.
The closeness centrality uses inward distance to a node, not outward. If you want to use outword distances apply
the function to [Link]()
1 Linton C. Freeman: Centrality in networks: I. Conceptual clarification. Social Networks 1:215-239, 1979. [Link]

socialnetworks/papers/[Link]
2 pg. 201 of Wasserman, S. and Faust, K., Social Network Analysis: Methods and Applications, 1994, Cambridge University Press.

214 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

In NetworkX 2.2 and earlier a bug caused Dijkstra’s algorithm to use the outward distance rather than the inward
distance. If you use a ‘distance’ keyword and a DiGraph, your results will change between v2.2 and v2.3.

References

[Link].incremental_closeness_centrality

incremental_closeness_centrality(G, edge, prev_cc=None, insertion=True, wf_improved=True)


Incremental closeness centrality for nodes.
Compute closeness centrality for nodes using level-based work filtering as described in Incremental Algorithms
for Closeness Centrality by Sariyuce et al.
Level-based work filtering detects unnecessary updates to the closeness centrality and filters them out.
— From “Incremental Algorithms for Closeness Centrality”:
Theorem 1: Let 𝐺 = (𝑉, 𝐸) be a graph and u and v be two vertices in V such that there is no edge (u, v) in E.
Let 𝐺′ = (𝑉, 𝐸 ∪ 𝑢𝑣) Then 𝑐𝑐[𝑠] = 𝑐𝑐′ [𝑠] if and only if |𝑑𝐺(𝑠, 𝑢) − 𝑑𝐺(𝑠, 𝑣)| ≤ 1.
Where 𝑑𝐺(𝑢, 𝑣) denotes the length of the shortest path between two vertices u, v in a graph G, cc[s] is the
closeness centrality for a vertex s in V, and cc’[s] is the closeness centrality for a vertex s in V, with the (u, v)
edge added. —
We use Theorem 1 to filter out updates when adding or removing an edge. When adding an edge (u, v), we
compute the shortest path lengths from all other nodes to u and to v before the node is added. When removing
an edge, we compute the shortest path lengths after the edge is removed. Then we apply Theorem 1 to use
previously computed closeness centrality for nodes where |𝑑𝐺(𝑠, 𝑢) − 𝑑𝐺(𝑠, 𝑣)| ≤ 1. This works only for
undirected, unweighted graphs; the distance argument is not supported.
Closeness centrality1 of a node u is the reciprocal of the sum of the shortest path distances from u to all n-1
other nodes. Since the sum of distances depends on the number of nodes in the graph, closeness is normalized
by the sum of minimum possible distances n-1.
𝑛−1
𝐶(𝑢) = ∑︀𝑛−1 ,
𝑣=1 𝑑(𝑣, 𝑢)

where d(v, u) is the shortest-path distance between v and u, and n is the number of nodes in the graph.
Notice that higher values of closeness indicate higher centrality.
Parameters
• G (graph) – A NetworkX graph
• edge (tuple) – The modified edge (u, v) in the graph.
• prev_cc (dictionary) – The previous closeness centrality for all nodes in the graph.
• insertion (bool, optional) – If True (default) the edge was inserted, otherwise it was deleted
from the graph.
• wf_improved (bool, optional (default=True)) – If True, scale by the fraction of nodes reach-
able. This gives the Wasserman and Faust improved formula. For single component graphs
it is the same as the original formula.
Returns nodes – Dictionary of nodes with closeness centrality as the value.
Return type dictionary
1 Freeman, L.C., 1979. Centrality in networks: I. Conceptual clarification. Social Networks 1, 215–239. [Link]
friedkin/Syllabi/Soc146/[Link]

3.7. Centrality 215


NetworkX Reference, Release 2.5

See also:
betweenness_centrality(), load_centrality(), eigenvector_centrality(),
degree_centrality(), closeness_centrality()

Notes

The closeness centrality is normalized to (n-1)/(|G|-1) where n is the number of nodes in the connected
part of graph containing the node. If the graph is not completely connected, this algorithm computes the close-
ness centrality for each connected part separately.

References

3.7.4 Current Flow Closeness

current_flow_closeness_centrality(G[, Compute current-flow closeness centrality for nodes.


. . . ])
information_centrality(G[, weight, dtype, Compute current-flow closeness centrality for nodes.
. . . ])

[Link].current_flow_closeness_centrality

current_flow_closeness_centrality(G, weight=None, dtype=<class 'float'>, solver='lu')


Compute current-flow closeness centrality for nodes.
Current-flow closeness centrality is variant of closeness centrality based on effective resistance between nodes
in a network. This metric is also known as information centrality.
Parameters
• G (graph) – A NetworkX graph.
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
• dtype (data type (default=float)) – Default data type for internal matrices. Set to np.float32
for lower memory consumption.
• solver (string (default=’lu’)) – Type of linear solver to use for computing the flow matrix.
Options are “full” (uses most memory), “lu” (recommended), and “cg” (uses least memory).
Returns nodes – Dictionary of nodes with current flow closeness centrality as the value.
Return type dictionary
See also:
closeness_centrality()

216 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Notes

The algorithm is from Brandes1 .


See also2 for the original definition of information centrality.

References

[Link].information_centrality

information_centrality(G, weight=None, dtype=<class 'float'>, solver='lu')


Compute current-flow closeness centrality for nodes.
Current-flow closeness centrality is variant of closeness centrality based on effective resistance between nodes
in a network. This metric is also known as information centrality.
Parameters
• G (graph) – A NetworkX graph.
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
• dtype (data type (default=float)) – Default data type for internal matrices. Set to np.float32
for lower memory consumption.
• solver (string (default=’lu’)) – Type of linear solver to use for computing the flow matrix.
Options are “full” (uses most memory), “lu” (recommended), and “cg” (uses least memory).
Returns nodes – Dictionary of nodes with current flow closeness centrality as the value.
Return type dictionary
See also:
closeness_centrality()

Notes

The algorithm is from Brandes1 .


See also2 for the original definition of information centrality.
1 Ulrik Brandes and Daniel Fleischer, Centrality Measures Based on Current Flow. Proc. 22nd Symp. Theoretical Aspects of Computer Science

(STACS ‘05). LNCS 3404, pp. 533-544. Springer-Verlag, 2005. [Link]


2 Karen Stephenson and Marvin Zelen: Rethinking centrality: Methods and examples. Social Networks 11(1):1-37, 1989. [Link]

1016/0378-8733(89)90016-6
1 Ulrik Brandes and Daniel Fleischer, Centrality Measures Based on Current Flow. Proc. 22nd Symp. Theoretical Aspects of Computer Science

(STACS ‘05). LNCS 3404, pp. 533-544. Springer-Verlag, 2005. [Link]


2 Karen Stephenson and Marvin Zelen: Rethinking centrality: Methods and examples. Social Networks 11(1):1-37, 1989. [Link]

1016/0378-8733(89)90016-6

3.7. Centrality 217


NetworkX Reference, Release 2.5

References

3.7.5 (Shortest Path) Betweenness

betweenness_centrality(G[, k, normalized, Compute the shortest-path betweenness centrality for


. . . ]) nodes.
betweenness_centrality_source(G[, . . . ])
betweenness_centrality_subset(G, sources, Compute betweenness centrality for a subset of nodes.
...)
edge_betweenness_centrality(G[, k, . . . ]) Compute betweenness centrality for edges.
edge_betweenness_centrality_subset(G, Compute betweenness centrality for edges for a subset
. . . [, . . . ]) of nodes.

[Link].betweenness_centrality

betweenness_centrality(G, k=None, normalized=True, weight=None, endpoints=False, seed=None)


Compute the shortest-path betweenness centrality for nodes.
Betweenness centrality of a node 𝑣 is the sum of the fraction of all-pairs shortest paths that pass through 𝑣
∑︁ 𝜎(𝑠, 𝑡|𝑣)
𝑐𝐵 (𝑣) =
𝜎(𝑠, 𝑡)
𝑠,𝑡∈𝑉

where 𝑉 is the set of nodes, 𝜎(𝑠, 𝑡) is the number of shortest (𝑠, 𝑡)-paths, and 𝜎(𝑠, 𝑡|𝑣) is the number of those
paths passing through some node 𝑣 other than 𝑠, 𝑡. If 𝑠 = 𝑡, 𝜎(𝑠, 𝑡) = 1, and if 𝑣 ∈ 𝑠, 𝑡, 𝜎(𝑠, 𝑡|𝑣) = 02 .
Parameters
• G (graph) – A NetworkX graph.
• k (int, optional (default=None)) – If k is not None use k node samples to estimate between-
ness. The value of k <= n where n is the number of nodes in the graph. Higher values give
better approximation.
• normalized (bool, optional) – If True the betweenness values are normalized by 2/
((n-1)(n-2)) for graphs, and 1/((n-1)(n-2)) for directed graphs where n is the
number of nodes in G.
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
• endpoints (bool, optional) – If True include the endpoints in the shortest path counts.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness. Note that this is only used if k is not None.
Returns nodes – Dictionary of nodes with betweenness centrality as the value.
Return type dictionary
See also:
edge_betweenness_centrality(), load_centrality()
2 Ulrik Brandes: On Variants of Shortest-Path Betweenness Centrality and their Generic Computation. Social Networks 30(2):136-145, 2008.

[Link]

218 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Notes

The algorithm is from Ulrik Brandes1 . See4 for the original first published version and2 for details on algorithms
for variations and related metrics.
For approximate betweenness calculations set k=#samples to use k nodes (“pivots”) to estimate the betweenness
values. For an estimate of the number of pivots needed see3 .
For weighted graphs the edge weights must be greater than zero. Zero edge weights can produce an infinite
number of equal length paths between pairs of nodes.
The total number of paths between source and target is counted differently for directed and undirected graphs.
Directed paths are easy to count. Undirected paths are tricky: should a path from “u” to “v” count as 1 undirected
path or as 2 directed paths?
For betweenness_centrality we report the number of undirected paths when G is undirected.
For betweenness_centrality_subset the reporting is different. If the source and target subsets are the same, then
we want to count undirected paths. But if the source and target subsets differ – for example, if sources is {0}
and targets is {1}, then we are only counting the paths in one direction. They are undirected paths but we are
counting them in a directed way. To count them as undirected paths, each should count as half a path.

References

[Link].betweenness_centrality_source

betweenness_centrality_source(G, normalized=True, weight=None, sources=None)

[Link].betweenness_centrality_subset

betweenness_centrality_subset(G, sources, targets, normalized=False, weight=None)


Compute betweenness centrality for a subset of nodes.
∑︁ 𝜎(𝑠, 𝑡|𝑣)
𝑐𝐵 (𝑣) =
𝜎(𝑠, 𝑡)
𝑠∈𝑆,𝑡∈𝑇

where 𝑆 is the set of sources, 𝑇 is the set of targets, 𝜎(𝑠, 𝑡) is the number of shortest (𝑠, 𝑡)-paths, and 𝜎(𝑠, 𝑡|𝑣)
is the number of those paths passing through some node 𝑣 other than 𝑠, 𝑡. If 𝑠 = 𝑡, 𝜎(𝑠, 𝑡) = 1, and if 𝑣 ∈ 𝑠, 𝑡,
𝜎(𝑠, 𝑡|𝑣) = 02 .
Parameters
• G (graph) – A NetworkX graph.
• sources (list of nodes) – Nodes to use as sources for shortest paths in betweenness
• targets (list of nodes) – Nodes to use as targets for shortest paths in betweenness
• normalized (bool, optional) – If True the betweenness values are normalized by 2/((𝑛 −
1)(𝑛 − 2)) for graphs, and 1/((𝑛 − 1)(𝑛 − 2)) for directed graphs where 𝑛 is the number of
nodes in G.
1 Ulrik Brandes: A Faster Algorithm for Betweenness Centrality. Journal of Mathematical Sociology 25(2):163-177, 2001. [Link]

[Link]/algo/publications/[Link]
4 Linton C. Freeman: A set of measures of centrality based on betweenness. Sociometry 40: 35–41, 1977 [Link]
3 Ulrik Brandes and Christian Pich: Centrality Estimation in Large Networks. International Journal of Bifurcation and Chaos 17(7):2303-2318,

2007. [Link]
2 Ulrik Brandes: On Variants of Shortest-Path Betweenness Centrality and their Generic Computation. Social Networks 30(2):136-145, 2008.

[Link]

3.7. Centrality 219


NetworkX Reference, Release 2.5

• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
Returns nodes – Dictionary of nodes with betweenness centrality as the value.
Return type dictionary
See also:
edge_betweenness_centrality(), load_centrality()

Notes

The basic algorithm is from1 .


For weighted graphs the edge weights must be greater than zero. Zero edge weights can produce an infinite
number of equal length paths between pairs of nodes.
The normalization might seem a little strange but it is designed to make betweenness_centrality(G) be the same
as betweenness_centrality_subset(G,sources=[Link](),targets=[Link]()).
The total number of paths between source and target is counted differently for directed and undirected graphs.
Directed paths are easy to count. Undirected paths are tricky: should a path from “u” to “v” count as 1 undirected
path or as 2 directed paths?
For betweenness_centrality we report the number of undirected paths when G is undirected.
For betweenness_centrality_subset the reporting is different. If the source and target subsets are the same, then
we want to count undirected paths. But if the source and target subsets differ – for example, if sources is {0}
and targets is {1}, then we are only counting the paths in one direction. They are undirected paths but we are
counting them in a directed way. To count them as undirected paths, each should count as half a path.

References

[Link].edge_betweenness_centrality

edge_betweenness_centrality(G, k=None, normalized=True, weight=None, seed=None)


Compute betweenness centrality for edges.
Betweenness centrality of an edge 𝑒 is the sum of the fraction of all-pairs shortest paths that pass through 𝑒
∑︁ 𝜎(𝑠, 𝑡|𝑒)
𝑐𝐵 (𝑒) =
𝜎(𝑠, 𝑡)
𝑠,𝑡∈𝑉

where 𝑉 is the set of nodes, 𝜎(𝑠, 𝑡) is the number of shortest (𝑠, 𝑡)-paths, and 𝜎(𝑠, 𝑡|𝑒) is the number of those
paths passing through edge 𝑒2 .
Parameters
• G (graph) – A NetworkX graph.
• k (int, optional (default=None)) – If k is not None use k node samples to estimate between-
ness. The value of k <= n where n is the number of nodes in the graph. Higher values give
better approximation.
1 Ulrik Brandes, A Faster Algorithm for Betweenness Centrality. Journal of Mathematical Sociology 25(2):163-177, 2001. [Link]

[Link]/algo/publications/[Link]
2 Ulrik Brandes: On Variants of Shortest-Path Betweenness Centrality and their Generic Computation. Social Networks 30(2):136-145, 2008.

[Link]

220 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

• normalized (bool, optional) – If True the betweenness values are normalized by 2/(𝑛(𝑛 −
1)) for graphs, and 1/(𝑛(𝑛 − 1)) for directed graphs where 𝑛 is the number of nodes in G.
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness. Note that this is only used if k is not None.
Returns edges – Dictionary of edges with betweenness centrality as the value.
Return type dictionary
See also:
betweenness_centrality(), edge_load()

Notes

The algorithm is from Ulrik Brandes1 .


For weighted graphs the edge weights must be greater than zero. Zero edge weights can produce an infinite
number of equal length paths between pairs of nodes.

References

[Link].edge_betweenness_centrality_subset

edge_betweenness_centrality_subset(G, sources, targets, normalized=False, weight=None)


Compute betweenness centrality for edges for a subset of nodes.
∑︁ 𝜎(𝑠, 𝑡|𝑒)
𝑐𝐵 (𝑣) =
𝜎(𝑠, 𝑡)
𝑠∈𝑆,𝑡∈𝑇

where 𝑆 is the set of sources, 𝑇 is the set of targets, 𝜎(𝑠, 𝑡) is the number of shortest (𝑠, 𝑡)-paths, and 𝜎(𝑠, 𝑡|𝑒)
is the number of those paths passing through edge 𝑒2 .
Parameters
• G (graph) – A networkx graph.
• sources (list of nodes) – Nodes to use as sources for shortest paths in betweenness
• targets (list of nodes) – Nodes to use as targets for shortest paths in betweenness
• normalized (bool, optional) – If True the betweenness values are normalized by 2/
(n(n-1)) for graphs, and 1/(n(n-1)) for directed graphs where n is the number of
nodes in G.
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
Returns edges – Dictionary of edges with Betweenness centrality as the value.
Return type dictionary
1 A Faster Algorithm for Betweenness Centrality. Ulrik Brandes, Journal of Mathematical Sociology 25(2):163-177, 2001. [Link]

[Link]/algo/publications/[Link]
2 Ulrik Brandes: On Variants of Shortest-Path Betweenness Centrality and their Generic Computation. Social Networks 30(2):136-145, 2008.

[Link]

3.7. Centrality 221


NetworkX Reference, Release 2.5

See also:
betweenness_centrality(), edge_load()

Notes

The basic algorithm is from1 .


For weighted graphs the edge weights must be greater than zero. Zero edge weights can produce an infinite
number of equal length paths between pairs of nodes.
The normalization might seem a little strange but it is the same as in
edge_betweenness_centrality() and is designed to make edge_betweenness_centrality(G) be the same as
edge_betweenness_centrality_subset(G,sources=[Link](),targets=[Link]()).

References

3.7.6 Current Flow Betweenness

current_flow_betweenness_centrality(G[, Compute current-flow betweenness centrality for nodes.


. . . ])
Compute current-flow betweenness centrality for edges.
edge_current_flow_betweenness_centrality(G)
Compute the approximate current-flow betweenness
approximate_current_flow_betweenness_centrality(G)
centrality for nodes.
Compute current-flow betweenness centrality for sub-
current_flow_betweenness_centrality_subset(G,
...) sets of nodes.
Compute current-flow betweenness centrality for edges
edge_current_flow_betweenness_centrality_subset(G,
...) using subsets of nodes.

[Link].current_flow_betweenness_centrality

current_flow_betweenness_centrality(G, normalized=True, weight=None, dtype=<class


'float'>, solver='full')
Compute current-flow betweenness centrality for nodes.
Current-flow betweenness centrality uses an electrical current model for information spreading in contrast to
betweenness centrality which uses shortest paths.
Current-flow betweenness centrality is also known as random-walk betweenness centrality2 .
Parameters
• G (graph) – A NetworkX graph
• normalized (bool, optional (default=True)) – If True the betweenness values are normalized
by 2/[(n-1)(n-2)] where n is the number of nodes in G.
• weight (string or None, optional (default=None)) – Key for edge data used as the edge
weight. If None, then use 1 as each edge weight.
• dtype (data type (float)) – Default data type for internal matrices. Set to np.float32 for lower
memory consumption.
1 Ulrik Brandes, A Faster Algorithm for Betweenness Centrality. Journal of Mathematical Sociology 25(2):163-177, 2001. [Link]

[Link]/algo/publications/[Link]
2 A measure of betweenness centrality based on random walks, M. E. J. Newman, Social Networks 27, 39-54 (2005).

222 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

• solver (string (default=’full’)) – Type of linear solver to use for computing the flow matrix.
Options are “full” (uses most memory), “lu” (recommended), and “cg” (uses least memory).
Returns nodes – Dictionary of nodes with betweenness centrality as the value.
Return type dictionary
See also:
approximate_current_flow_betweenness_centrality(), betweenness_centrality(),
edge_betweenness_centrality(), edge_current_flow_betweenness_centrality()

Notes

Current-flow betweenness can be computed in 𝑂(𝐼(𝑛 − 1) + 𝑚𝑛 log 𝑛) time1 , where 𝐼(𝑛 − 1) is the time
3
√ the inverse Laplacian. For a full matrix this is 𝑂(𝑛 ) but using sparse methods you can
needed to compute
achieve 𝑂(𝑛𝑚 𝑘) where 𝑘 is the Laplacian matrix condition number.
The space required is 𝑂(𝑛𝑤) where 𝑤 is the width of the sparse Laplacian matrix. Worse case is 𝑤 = 𝑛 for
𝑂(𝑛2 ).
If the edges have a ‘weight’ attribute they will be used as weights in this algorithm. Unspecified weights are set
to 1.

References

[Link].edge_current_flow_betweenness_centrality

edge_current_flow_betweenness_centrality(G, normalized=True, weight=None,


dtype=<class 'float'>, solver='full')
Compute current-flow betweenness centrality for edges.
Current-flow betweenness centrality uses an electrical current model for information spreading in contrast to
betweenness centrality which uses shortest paths.
Current-flow betweenness centrality is also known as random-walk betweenness centrality2 .
Parameters
• G (graph) – A NetworkX graph
• normalized (bool, optional (default=True)) – If True the betweenness values are normalized
by 2/[(n-1)(n-2)] where n is the number of nodes in G.
• weight (string or None, optional (default=None)) – Key for edge data used as the edge
weight. If None, then use 1 as each edge weight.
• dtype (data type (default=float)) – Default data type for internal matrices. Set to np.float32
for lower memory consumption.
• solver (string (default=’full’)) – Type of linear solver to use for computing the flow matrix.
Options are “full” (uses most memory), “lu” (recommended), and “cg” (uses least memory).
Returns nodes – Dictionary of edge tuples with betweenness centrality as the value.
Return type dictionary
1 Centrality Measures Based on Current Flow. Ulrik Brandes and Daniel Fleischer, Proc. 22nd Symp. Theoretical Aspects of Computer Science

(STACS ‘05). LNCS 3404, pp. 533-544. Springer-Verlag, 2005. [Link]


2 A measure of betweenness centrality based on random walks, M. E. J. Newman, Social Networks 27, 39-54 (2005).

3.7. Centrality 223


NetworkX Reference, Release 2.5

Raises NetworkXError – The algorithm does not support DiGraphs. If the input graph is an
instance of DiGraph class, NetworkXError is raised.
See also:
betweenness_centrality(), edge_betweenness_centrality(),
current_flow_betweenness_centrality()

Notes

Current-flow betweenness can be computed in 𝑂(𝐼(𝑛 − 1) + 𝑚𝑛 log 𝑛) time1 , where 𝐼(𝑛 − 1) is the time
3
√ the inverse Laplacian. For a full matrix this is 𝑂(𝑛 ) but using sparse methods you can
needed to compute
achieve 𝑂(𝑛𝑚 𝑘) where 𝑘 is the Laplacian matrix condition number.
The space required is 𝑂(𝑛𝑤) where 𝑤 is the width of the sparse Laplacian matrix. Worse case is 𝑤 = 𝑛 for
𝑂(𝑛2 ).
If the edges have a ‘weight’ attribute they will be used as weights in this algorithm. Unspecified weights are set
to 1.

References

[Link].approximate_current_flow_betweenness_centrality

approximate_current_flow_betweenness_centrality(G, normalized=True, weight=None,


dtype=<class 'float'>, solver='full', ep-
silon=0.5, kmax=10000, seed=None)
Compute the approximate current-flow betweenness centrality for nodes.
Approximates the current-flow betweenness centrality within absolute error of epsilon with high probability1 .
Parameters
• G (graph) – A NetworkX graph
• normalized (bool, optional (default=True)) – If True the betweenness values are normalized
by 2/[(n-1)(n-2)] where n is the number of nodes in G.
• weight (string or None, optional (default=None)) – Key for edge data used as the edge
weight. If None, then use 1 as each edge weight.
• dtype (data type (float)) – Default data type for internal matrices. Set to np.float32 for lower
memory consumption.
• solver (string (default=’full’)) – Type of linear solver to use for computing the flow matrix.
Options are “full” (uses most memory), “lu” (recommended), and “cg” (uses least memory).
• epsilon (float) – Absolute error tolerance.
• kmax (int) – Maximum number of sample node pairs to use for approximation.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
Returns nodes – Dictionary of nodes with betweenness centrality as the value.
Return type dictionary
1 Centrality Measures Based on Current Flow. Ulrik Brandes and Daniel Fleischer, Proc. 22nd Symp. Theoretical Aspects of Computer Science

(STACS ‘05). LNCS 3404, pp. 533-544. Springer-Verlag, 2005. [Link]


1 Ulrik Brandes and Daniel Fleischer: Centrality Measures Based on Current Flow. Proc. 22nd Symp. Theoretical Aspects of Computer Science

(STACS ‘05). LNCS 3404, pp. 533-544. Springer-Verlag, 2005. [Link]

224 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

See also:
current_flow_betweenness_centrality()

Notes

The running time is 𝑂((1/𝜖2 )𝑚 𝑘 log 𝑛) and the space required is 𝑂(𝑚) for 𝑛 nodes and 𝑚 edges.
If the edges have a ‘weight’ attribute they will be used as weights in this algorithm. Unspecified weights are set
to 1.

References

[Link].current_flow_betweenness_centrality_subset

current_flow_betweenness_centrality_subset(G, sources, targets, normalized=True,


weight=None, dtype=<class 'float'>,
solver='lu')
Compute current-flow betweenness centrality for subsets of nodes.
Current-flow betweenness centrality uses an electrical current model for information spreading in contrast to
betweenness centrality which uses shortest paths.
Current-flow betweenness centrality is also known as random-walk betweenness centrality2 .
Parameters
• G (graph) – A NetworkX graph
• sources (list of nodes) – Nodes to use as sources for current
• targets (list of nodes) – Nodes to use as sinks for current
• normalized (bool, optional (default=True)) – If True the betweenness values are normalized
by b=b/(n-1)(n-2) where n is the number of nodes in G.
• weight (string or None, optional (default=None)) – Key for edge data used as the edge
weight. If None, then use 1 as each edge weight.
• dtype (data type (float)) – Default data type for internal matrices. Set to np.float32 for lower
memory consumption.
• solver (string (default=’lu’)) – Type of linear solver to use for computing the flow matrix.
Options are “full” (uses most memory), “lu” (recommended), and “cg” (uses least memory).
Returns nodes – Dictionary of nodes with betweenness centrality as the value.
Return type dictionary
See also:
approximate_current_flow_betweenness_centrality(), betweenness_centrality(),
edge_betweenness_centrality(), edge_current_flow_betweenness_centrality()
2 A measure of betweenness centrality based on random walks, M. E. J. Newman, Social Networks 27, 39-54 (2005).

3.7. Centrality 225


NetworkX Reference, Release 2.5

Notes

Current-flow betweenness can be computed in 𝑂(𝐼(𝑛 − 1) + 𝑚𝑛 log 𝑛) time1 , where 𝐼(𝑛 − 1) is the time
3
√ the inverse Laplacian. For a full matrix this is 𝑂(𝑛 ) but using sparse methods you can
needed to compute
achieve 𝑂(𝑛𝑚 𝑘) where 𝑘 is the Laplacian matrix condition number.
The space required is 𝑂(𝑛𝑤) where 𝑤 is the width of the sparse Laplacian matrix. Worse case is 𝑤 = 𝑛 for
𝑂(𝑛2 ).
If the edges have a ‘weight’ attribute they will be used as weights in this algorithm. Unspecified weights are set
to 1.

References

[Link].edge_current_flow_betweenness_centrality_subset

edge_current_flow_betweenness_centrality_subset(G, sources, targets, normalized=True,


weight=None, dtype=<class 'float'>,
solver='lu')
Compute current-flow betweenness centrality for edges using subsets of nodes.
Current-flow betweenness centrality uses an electrical current model for information spreading in contrast to
betweenness centrality which uses shortest paths.
Current-flow betweenness centrality is also known as random-walk betweenness centrality2 .
Parameters
• G (graph) – A NetworkX graph
• sources (list of nodes) – Nodes to use as sources for current
• targets (list of nodes) – Nodes to use as sinks for current
• normalized (bool, optional (default=True)) – If True the betweenness values are normalized
by b=b/(n-1)(n-2) where n is the number of nodes in G.
• weight (string or None, optional (default=None)) – Key for edge data used as the edge
weight. If None, then use 1 as each edge weight.
• dtype (data type (float)) – Default data type for internal matrices. Set to np.float32 for lower
memory consumption.
• solver (string (default=’lu’)) – Type of linear solver to use for computing the flow matrix.
Options are “full” (uses most memory), “lu” (recommended), and “cg” (uses least memory).
Returns nodes – Dictionary of edge tuples with betweenness centrality as the value.
Return type dict
See also:
betweenness_centrality(), edge_betweenness_centrality(),
current_flow_betweenness_centrality()
1 Centrality Measures Based on Current Flow. Ulrik Brandes and Daniel Fleischer, Proc. 22nd Symp. Theoretical Aspects of Computer Science

(STACS ‘05). LNCS 3404, pp. 533-544. Springer-Verlag, 2005. [Link]


2 A measure of betweenness centrality based on random walks, M. E. J. Newman, Social Networks 27, 39-54 (2005).

226 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Notes

Current-flow betweenness can be computed in 𝑂(𝐼(𝑛 − 1) + 𝑚𝑛 log 𝑛) time1 , where 𝐼(𝑛 − 1) is the time
3
√ the inverse Laplacian. For a full matrix this is 𝑂(𝑛 ) but using sparse methods you can
needed to compute
achieve 𝑂(𝑛𝑚 𝑘) where 𝑘 is the Laplacian matrix condition number.
The space required is 𝑂(𝑛𝑤) where 𝑤 is the width of the sparse Laplacian matrix. Worse case is 𝑤 = 𝑛 for
𝑂(𝑛2 ).
If the edges have a ‘weight’ attribute they will be used as weights in this algorithm. Unspecified weights are set
to 1.

References

3.7.7 Communicability Betweenness

Returns subgraph communicability for all pairs of nodes


communicability_betweenness_centrality(G[,
. . . ]) in G.

[Link].communicability_betweenness_centrality

communicability_betweenness_centrality(G, normalized=True)
Returns subgraph communicability for all pairs of nodes in G.
Communicability betweenness measure makes use of the number of walks connecting every pair of nodes as the
basis of a betweenness centrality measure.
Parameters G (graph)
Returns nodes – Dictionary of nodes with communicability betweenness as the value.
Return type dictionary
Raises NetworkXError – If the graph is not undirected and simple.

Notes

Let G=(V,E) be a simple undirected graph with n nodes and m edges, and A denote the adjacency matrix of G.
Let G(r)=(V,E(r)) be the graph resulting from removing all edges connected to node r but not the node
itself.
The adjacency matrix for G(r) is A+E(r), where E(r) has nonzeros only in row and column r.
The subraph betweenness of a node r is1
1 ∑︁ ∑︁ 𝐺𝑝𝑟𝑞
𝜔𝑟 = , 𝑝 ̸= 𝑞, 𝑞 ̸= 𝑟,
𝐶 𝑝 𝑞 𝐺𝑝𝑞

where G_{prq}=(e^{A}_{pq} - (e^{A+E(r)})_{pq} is the number of walks involving node r,


G_{pq}=(e^{A})_{pq} is the number of closed walks starting at node p and ending at node q, and
C=(n-1)^{2}-(n-1) is a normalization factor equal to the number of terms in the sum.
1 Centrality Measures Based on Current Flow. Ulrik Brandes and Daniel Fleischer, Proc. 22nd Symp. Theoretical Aspects of Computer Science

(STACS ‘05). LNCS 3404, pp. 533-544. Springer-Verlag, 2005. [Link]


1 Ernesto Estrada, Desmond J. Higham, Naomichi Hatano, “Communicability Betweenness in Complex Networks” Physica A 388 (2009) 764-

774. [Link]

3.7. Centrality 227


NetworkX Reference, Release 2.5

The resulting omega_{r} takes values between zero and one. The lower bound cannot be attained for a
connected graph, and the upper bound is attained in the star graph.

References

Examples

>>> G = [Link]([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
>>> cbc = nx.communicability_betweenness_centrality(G)
>>> print([f"{node} {cbc[node]:0.2f}" for node in sorted(cbc)])
['0 0.03', '1 0.45', '2 0.51', '3 0.45', '4 0.40', '5 0.19', '6 0.03']

3.7.8 Group Centrality

group_betweenness_centrality(G, C[, . . . ]) Compute the group betweenness centrality for a group


of nodes.
group_closeness_centrality(G, S[, weight]) Compute the group closeness centrality for a group of
nodes.
group_degree_centrality(G, S) Compute the group degree centrality for a group of
nodes.
group_in_degree_centrality(G, S) Compute the group in-degree centrality for a group of
nodes.
group_out_degree_centrality(G, S) Compute the group out-degree centrality for a group of
nodes.

[Link].group_betweenness_centrality

group_betweenness_centrality(G, C, normalized=True, weight=None)


Compute the group betweenness centrality for a group of nodes.
Group betweenness centrality of a group of nodes 𝐶 is the sum of the fraction of all-pairs shortest paths that
pass through any vertex in 𝐶
∑︁ 𝜎(𝑠, 𝑡|𝐶)
𝑐𝐵 (𝐶) =
𝜎(𝑠, 𝑡)
𝑠,𝑡∈𝑉 −𝐶;𝑠<𝑡

where 𝑉 is the set of nodes, 𝜎(𝑠, 𝑡) is the number of shortest (𝑠, 𝑡)-paths, and 𝜎(𝑠, 𝑡|𝐶) is the number of those
paths passing through some node in group 𝐶. Note that (𝑠, 𝑡) are not members of the group (𝑉 − 𝐶 is the set of
nodes in 𝑉 that are not in 𝐶).
Parameters
• G (graph) – A NetworkX graph.
• C (list or set) – C is a group of nodes which belong to G, for which group betweenness
centrality is to be calculated.
• normalized (bool, optional) – If True, group betweenness is normalized by 2/
((|V|-|C|)(|V|-|C|-1)) for graphs and 1/((|V|-|C|)(|V|-|C|-1)) for di-
rected graphs where |V| is the number of nodes in G and |C| is the number of nodes in
C.
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.

228 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Raises NodeNotFound – If node(s) in C are not present in G.


Returns betweenness – Group betweenness centrality of the group C.
Return type float
See also:
betweenness_centrality()

Notes

The measure is described in1 . The algorithm is an extension of the one proposed by Ulrik Brandes for between-
ness centrality of nodes. Group betweenness is also mentioned in his paper2 along with the algorithm. The
importance of the measure is discussed in3 .
The number of nodes in the group must be a maximum of n - 2 where n is the total number of nodes in the
graph.
For weighted graphs the edge weights must be greater than zero. Zero edge weights can produce an infinite
number of equal length paths between pairs of nodes.

References

[Link].group_closeness_centrality

group_closeness_centrality(G, S, weight=None)
Compute the group closeness centrality for a group of nodes.
Group closeness centrality of a group of nodes 𝑆 is a measure of how close the group is to the other nodes in
the graph.

|𝑉 − 𝑆|
𝑐𝑐𝑙𝑜𝑠𝑒 (𝑆) = ∑︀
𝑣∈𝑉 −𝑆 𝑑𝑆,𝑣
𝑑𝑆,𝑣 = 𝑚𝑖𝑛𝑢∈𝑆 (𝑑𝑢,𝑣 )

where 𝑉 is the set of nodes, 𝑑𝑆,𝑣 is the distance of the group 𝑆 from 𝑣 defined as above. (𝑉 − 𝑆 is the set of
nodes in 𝑉 that are not in 𝑆).
Parameters
• G (graph) – A NetworkX graph.
• S (list or set) – S is a group of nodes which belong to G, for which group closeness centrality
is to be calculated.
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
Raises NodeNotFound – If node(s) in S are not present in G.
Returns closeness – Group closeness centrality of the group S.
Return type float
1 M G Everett and S P Borgatti: The Centrality of Groups and Classes. Journal of Mathematical Sociology. 23(3): 181-201. 1999. http:

//[Link]/borgatti/group_centrality.htm
2 Ulrik Brandes: On Variants of Shortest-Path Betweenness Centrality and their Generic Computation. Social Networks 30(2):136-145, 2008.

[Link]
3 Sourav Medya et. al.: Group Centrality Maximization via Network Design. SIAM International Conference on Data Mining, SDM 2018,

126–134. [Link]

3.7. Centrality 229


NetworkX Reference, Release 2.5

See also:
closeness_centrality()

Notes

The measure was introduced in1 . The formula implemented here is described in2 .
Higher values of closeness indicate greater centrality.
It is assumed that 1 / 0 is 0 (required in the case of directed graphs, or when a shortest path length is 0).
The number of nodes in the group must be a maximum of n - 1 where n is the total number of nodes in the
graph.
For directed graphs, the incoming distance is utilized here. To use the outward distance, act on [Link]().
For weighted graphs the edge weights must be greater than zero. Zero edge weights can produce an infinite
number of equal length paths between pairs of nodes.

References

[Link].group_degree_centrality

group_degree_centrality(G, S)
Compute the group degree centrality for a group of nodes.
Group degree centrality of a group of nodes 𝑆 is the fraction of non-group members connected to group mem-
bers.
Parameters
• G (graph) – A NetworkX graph.
• S (list or set) – S is a group of nodes which belong to G, for which group degree centrality
is to be calculated.
Raises NetworkXError – If node(s) in S are not in G.
Returns centrality – Group degree centrality of the group S.
Return type float
See also:
degree_centrality(), group_in_degree_centrality(), group_out_degree_centrality()
1 M G Everett and S P Borgatti: The Centrality of Groups and Classes. Journal of Mathematical Sociology. 23(3): 181-201. 1999. http:

//[Link]/borgatti/group_centrality.htm
2 J. Zhao et. al.: Measuring and Maximizing Group Closeness Centrality over Disk Resident Graphs. WWWConference Proceedings, 2014.

689-694. [Link]

230 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Notes

The measure was introduced in1 .


The number of nodes in the group must be a maximum of n - 1 where n is the total number of nodes in the
graph.

References

[Link].group_in_degree_centrality

group_in_degree_centrality(G, S)
Compute the group in-degree centrality for a group of nodes.
Group in-degree centrality of a group of nodes 𝑆 is the fraction of non-group members connected to group
members by incoming edges.
Parameters
• G (graph) – A NetworkX graph.
• S (list or set) – S is a group of nodes which belong to G, for which group in-degree centrality
is to be calculated.
Returns centrality – Group in-degree centrality of the group S.
Return type float
Raises
• NetworkXNotImplemented – If G is undirected.
• NodeNotFound – If node(s) in S are not in G.
See also:
degree_centrality(), group_degree_centrality(), group_out_degree_centrality()

Notes

The number of nodes in the group must be a maximum of n - 1 where n is the total number of nodes in the
graph.
[Link](i) gives nodes with an outward edge from i, in a DiGraph, so for group in-degree centrality,
the reverse graph is used.

[Link].group_out_degree_centrality

group_out_degree_centrality(G, S)
Compute the group out-degree centrality for a group of nodes.
Group out-degree centrality of a group of nodes 𝑆 is the fraction of non-group members connected to group
members by outgoing edges.
Parameters
• G (graph) – A NetworkX graph.
1 M G Everett and S P Borgatti: The Centrality of Groups and Classes. Journal of Mathematical Sociology. 23(3): 181-201. 1999. http:

//[Link]/borgatti/group_centrality.htm

3.7. Centrality 231


NetworkX Reference, Release 2.5

• S (list or set) – S is a group of nodes which belong to G, for which group in-degree centrality
is to be calculated.
Returns centrality – Group out-degree centrality of the group S.
Return type float
Raises
• NetworkXNotImplemented – If G is undirected.
• NodeNotFound – If node(s) in S are not in G.
See also:
degree_centrality(), group_degree_centrality(), group_in_degree_centrality()

Notes

The number of nodes in the group must be a maximum of n - 1 where n is the total number of nodes in the
graph.
[Link](i) gives nodes with an outward edge from i, in a DiGraph, so for group out-degree centrality,
the graph itself is used.

3.7.9 Load

load_centrality(G[, v, cutoff, normalized, . . . ]) Compute load centrality for nodes.


edge_load_centrality(G[, cutoff]) Compute edge load.

[Link].load_centrality

load_centrality(G, v=None, cutoff=None, normalized=True, weight=None)


Compute load centrality for nodes.
The load centrality of a node is the fraction of all shortest paths that pass through that node.
Parameters
• G (graph) – A networkx graph.
• normalized (bool, optional (default=True)) – If True the betweenness values are normalized
by b=b/(n-1)(n-2) where n is the number of nodes in G.
• weight (None or string, optional (default=None)) – If None, edge weights are ignored.
Otherwise holds the name of the edge attribute used as weight.
• cutoff (bool, optional (default=None)) – If specified, only consider paths of length <= cut-
off.
Returns nodes – Dictionary of nodes with centrality as the value.
Return type dictionary
See also:
betweenness_centrality()

232 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Notes

Load centrality is slightly different than betweenness. It was originally introduced by2 . For this load algorithm
see1 .

References

[Link].edge_load_centrality

edge_load_centrality(G, cutoff=False)
Compute edge load.
WARNING: This concept of edge load has not been analysed or discussed outside of NetworkX that we know
of. It is based loosely on load_centrality in the sense that it counts the number of shortest paths which cross
each edge. This function is for demonstration and testing purposes.
Parameters
• G (graph) – A networkx graph
• cutoff (bool, optional (default=False)) – If specified, only consider paths of length <= cut-
off.
Returns
• A dict keyed by edge 2-tuple to the number of shortest paths
• which use that edge. Where more than one path is shortest
• the count is divided equally among paths.

3.7.10 Subgraph

subgraph_centrality(G) Returns subgraph centrality for each node in G.


subgraph_centrality_exp(G) Returns the subgraph centrality for each node of G.
estrada_index(G) Returns the Estrada index of a the graph G.

[Link].subgraph_centrality

subgraph_centrality(G)
Returns subgraph centrality for each node in G.
Subgraph centrality of a node n is the sum of weighted closed walks of all lengths starting and ending at node
n. The weights decrease with path length. Each closed walk is associated with a connected subgraph (1 ).
Parameters G (graph)
Returns nodes – Dictionary of nodes with subgraph centrality as the value.
Return type dictionary
2 Kwang-Il Goh, Byungnam Kahng and Doochul Kim Universal behavior of Load Distribution in Scale-Free Networks. Physical Review Letters

87(27):1–4, 2001. [Link]


1 Mark E. J. Newman: Scientific collaboration networks. II. Shortest paths, weighted networks, and centrality. Physical Review E 64, 016132,

2001. [Link]
1 Ernesto Estrada, Juan A. Rodriguez-Velazquez, “Subgraph centrality in complex networks”, Physical Review E 71, 056103 (2005). https:

//[Link]/abs/cond-mat/0504730

3.7. Centrality 233


NetworkX Reference, Release 2.5

Raises NetworkXError – If the graph is not undirected and simple.


See also:

subgraph_centrality_exp() Alternative algorithm of the subgraph centrality for each node of G.

Notes

This version of the algorithm computes eigenvalues and eigenvectors of the adjacency matrix.
Subgraph centrality of a node u in G can be found using a spectral decomposition of the adjacency matrix1 ,
𝑁
∑︁
𝑆𝐶(𝑢) = (𝑣𝑗𝑢 )2 𝑒𝜆𝑗 ,
𝑗=1

where v_j is an eigenvector of the adjacency matrix A of G corresponding corresponding to the eigenvalue
lambda_j.

Examples

(Example from1 ) >>> G = [Link]( . . . [ . . . (1, 2), . . . (1, 5), . . . (1, 8), . . . (2, 3), . . . (2, 8), . . . (3, 4), . . .
(3, 6), . . . (4, 5), . . . (4, 7), . . . (5, 6), . . . (6, 7), . . . (7, 8), . . . ] . . . ) >>> sc = nx.subgraph_centrality(G)
>>> print([f”{node} {sc[node]:0.2f}” for node in sorted(sc)]) [‘1 3.90’, ‘2 3.90’, ‘3 3.64’, ‘4 3.71’, ‘5 3.64’, ‘6
3.71’, ‘7 3.64’, ‘8 3.90’]

References

[Link].subgraph_centrality_exp

subgraph_centrality_exp(G)
Returns the subgraph centrality for each node of G.
Subgraph centrality of a node n is the sum of weighted closed walks of all lengths starting and ending at node
n. The weights decrease with path length. Each closed walk is associated with a connected subgraph (1 ).
Parameters G (graph)
Returns nodes – Dictionary of nodes with subgraph centrality as the value.
Return type dictionary
Raises NetworkXError – If the graph is not undirected and simple.
See also:

subgraph_centrality() Alternative algorithm of the subgraph centrality for each node of G.


1 Ernesto Estrada, Juan A. Rodriguez-Velazquez, “Subgraph centrality in complex networks”, Physical Review E 71, 056103 (2005). https:
//[Link]/abs/cond-mat/0504730

234 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Notes

This version of the algorithm exponentiates the adjacency matrix.


The subgraph centrality of a node u in G can be found using the matrix exponential of the adjacency matrix of
G1 ,

𝑆𝐶(𝑢) = (𝑒𝐴 )𝑢𝑢 .

References

Examples

(Example from1 ) >>> G = [Link]( . . . [ . . . (1, 2), . . . (1, 5), . . . (1, 8), . . . (2, 3), . . . (2, 8), . . . (3, 4), . . .
(3, 6), . . . (4, 5), . . . (4, 7), . . . (5, 6), . . . (6, 7), . . . (7, 8), . . . ] . . . ) >>> sc = nx.subgraph_centrality_exp(G)
>>> print([f”{node} {sc[node]:0.2f}” for node in sorted(sc)]) [‘1 3.90’, ‘2 3.90’, ‘3 3.64’, ‘4 3.71’, ‘5 3.64’, ‘6
3.71’, ‘7 3.64’, ‘8 3.90’]

[Link].estrada_index

estrada_index(G)
Returns the Estrada index of a the graph G.
The Estrada Index is a topological index of folding or 3D “compactness” (1 ).
Parameters G (graph)
Returns estrada index
Return type float
Raises NetworkXError – If the graph is not undirected and simple.

Notes

Let G=(V,E) be a simple undirected graph with n nodes and let


lambda_{1}leqlambda_{2}leqcdotslambda_{n} be a non-increasing ordering of the eigen-
values of its adjacency matrix A. The Estrada index is (1 ,2 )
𝑛
∑︁
𝐸𝐸(𝐺) = 𝑒𝜆𝑗 .
𝑗=1
1 E. Estrada, “Characterization of 3D molecular structure”, Chem. Phys. Lett. 319, 713 (2000). [Link]
2 José Antonio de la Peñaa, Ivan Gutman, Juan Rada, “Estimating the Estrada index”, Linear Algebra and its Applications. 427, 1 (2007).

[Link]

3.7. Centrality 235


NetworkX Reference, Release 2.5

References

Examples

>>> G = [Link]([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
>>> ei = nx.estrada_index(G)
>>> print(f"{ei:0.5}")
20.55

3.7.11 Harmonic Centrality

harmonic_centrality(G[, nbunch, distance]) Compute harmonic centrality for nodes.

[Link].harmonic_centrality

harmonic_centrality(G, nbunch=None, distance=None)


Compute harmonic centrality for nodes.
Harmonic centrality1 of a node u is the sum of the reciprocal of the shortest path distances from all other nodes
to u
∑︁ 1
𝐶(𝑢) =
𝑑(𝑣, 𝑢)
𝑣̸=𝑢

where d(v, u) is the shortest-path distance between v and u.


Notice that higher values indicate higher centrality.
Parameters
• G (graph) – A NetworkX graph
• nbunch (container) – Container of nodes. If provided harmonic centrality will be computed
only over the nodes in nbunch.
• distance (edge attribute key, optional (default=None)) – Use the specified edge attribute as
the edge distance in shortest path calculations. If None, then each edge will have distance
equal to 1.
Returns nodes – Dictionary of nodes with harmonic centrality as the value.
Return type dictionary
See also:
betweenness_centrality(), load_centrality(), eigenvector_centrality(),
degree_centrality(), closeness_centrality()
1 Boldi, Paolo, and Sebastiano Vigna. “Axioms for centrality.” Internet Mathematics 10.3-4 (2014): 222-262.

236 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Notes

If the ‘distance’ keyword is set to an edge attribute key then the shortest-path length will be computed using
Dijkstra’s algorithm with that edge attribute as the edge weight.

References

3.7.12 Dispersion

dispersion(G[, u, v, normalized, alpha, b, c]) Calculate dispersion between u and v in G.

[Link]

dispersion(G, u=None, v=None, normalized=True, alpha=1.0, b=0.0, c=0.0)


Calculate dispersion between u and v in G.
A link between two actors (u and v) has a high dispersion when their mutual ties (s and t) are not well connected
with each other.
Parameters
• G (graph) – A NetworkX graph.
• u (node, optional) – The source for the dispersion score (e.g. ego node of the network).
• v (node, optional) – The target of the dispersion score if specified.
• normalized (bool) – If True (default) normalize by the embededness of the nodes (u and v).
Returns nodes – If u (v) is specified, returns a dictionary of nodes with dispersion score for all
“target” (“source”) nodes. If neither u nor v is specified, returns a dictionary of dictionaries for
all nodes ‘u’ in the graph with a dispersion score for each node ‘v’.
Return type dictionary

Notes

This implementation follows Lars Backstrom and Jon Kleinberg1 . Typical usage would be to run dispersion on
the ego network 𝐺𝑢 if 𝑢 were specified. Running dispersion() with neither 𝑢 nor 𝑣 specified can take some
time to complete.

References

3.7.13 Reaching

local_reaching_centrality(G, v[, paths, Returns the local reaching centrality of a node in a di-
. . . ]) rected graph.
global_reaching_centrality(G[, weight, Returns the global reaching centrality of a directed
. . . ]) graph.
1 Romantic Partnerships and the Dispersion of Social Ties: A Network Analysis of Relationship Status on Facebook. Lars Backstrom, Jon

Kleinberg. [Link]

3.7. Centrality 237


NetworkX Reference, Release 2.5

[Link].local_reaching_centrality

local_reaching_centrality(G, v, paths=None, weight=None, normalized=True)


Returns the local reaching centrality of a node in a directed graph.
The local reaching centrality of a node in a directed graph is the proportion of other nodes reachable from that
node1 .
Parameters
• G (DiGraph) – A NetworkX DiGraph.
• v (node) – A node in the directed graph G.
• paths (dictionary (default=None)) – If this is not None it must be a dictionary rep-
resentation of single-source shortest paths, as computed by, for example, networkx.
shortest_path() with source node v. Use this keyword argument if you intend to
invoke this function many times but don’t want the paths to be recomputed each time.
• weight (None or string, optional (default=None)) – Attribute to use for edge weights. If
None, each edge weight is assumed to be one. A higher weight implies a stronger connec-
tion between nodes and a shorter path length.
• normalized (bool, optional (default=True)) – Whether to normalize the edge weights by
the total sum of edge weights.
Returns h – The local reaching centrality of the node v in the graph G.
Return type float

Examples

>>> G = [Link]()
>>> G.add_edges_from([(1, 2), (1, 3)])
>>> nx.local_reaching_centrality(G, 3)
0.0
>>> G.add_edge(3, 2)
>>> nx.local_reaching_centrality(G, 3)
0.5

See also:
global_reaching_centrality()

References

[Link].global_reaching_centrality

global_reaching_centrality(G, weight=None, normalized=True)


Returns the global reaching centrality of a directed graph.
The global reaching centrality of a weighted directed graph is the average over all nodes of the difference
between the local reaching centrality of the node and the greatest local reaching centrality of any node in the
graph1 . For more information on the local reaching centrality, see local_reaching_centrality().
1 Mones, Enys, Lilla Vicsek, and Tamás Vicsek. “Hierarchy Measure for Complex Networks.” PLoS ONE 7.3 (2012): e33799. [Link]

10.1371/[Link].0033799
1 Mones, Enys, Lilla Vicsek, and Tamás Vicsek. “Hierarchy Measure for Complex Networks.” PLoS ONE 7.3 (2012): e33799. [Link]

10.1371/[Link].0033799

238 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Informally, the local reaching centrality is the proportion of the graph that is reachable from the neighbors of
the node.
Parameters
• G (DiGraph) – A networkx DiGraph.
• weight (None or string, optional (default=None)) – Attribute to use for edge weights. If
None, each edge weight is assumed to be one. A higher weight implies a stronger connec-
tion between nodes and a shorter path length.
• normalized (bool, optional (default=True)) – Whether to normalize the edge weights by
the total sum of edge weights.
Returns h – The global reaching centrality of the graph.
Return type float

Examples

>>> G = [Link]()
>>> G.add_edge(1, 2)
>>> G.add_edge(1, 3)
>>> nx.global_reaching_centrality(G)
1.0
>>> G.add_edge(3, 2)
>>> nx.global_reaching_centrality(G)
0.75

See also:
local_reaching_centrality()

References

3.7.14 Percolation

percolation_centrality(G[, attribute, . . . ]) Compute the percolation centrality for nodes.

[Link].percolation_centrality

percolation_centrality(G, attribute='percolation', states=None, weight=None)


Compute the percolation centrality for nodes.
Percolation centrality of a node 𝑣, at a given time, is defined as the proportion of ‘percolated paths’ that go
through that node.
This measure quantifies relative impact of nodes based on their topological connectivity, as well as their perco-
lation states.
Percolation states of nodes are used to depict network percolation scenarios (such as during infection transmis-
sion in a social network of individuals, spreading of computer viruses on computer networks, or transmission
of disease over a network of towns) over time. In this measure usually the percolation state is expressed as a
decimal between 0.0 and 1.0.
When all nodes are in the same percolated state this measure is equivalent to betweenness centrality.

3.7. Centrality 239


NetworkX Reference, Release 2.5

Parameters
• G (graph) – A NetworkX graph.
• attribute (None or string, optional (default=’percolation’)) – Name of the node attribute to
use for percolation state, used if states is None.
• states (None or dict, optional (default=None)) – Specify percolation states for the nodes,
nodes as keys states as values.
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
Returns nodes – Dictionary of nodes with percolation centrality as the value.
Return type dictionary
See also:
betweenness_centrality()

Notes

The algorithm is from Mahendra Piraveenan, Mikhail Prokopenko, and Liaquat Hossain1 Pair dependecies are
calculated and accumulated using2
For weighted graphs the edge weights must be greater than zero. Zero edge weights can produce an infinite
number of equal length paths between pairs of nodes.

References

3.7.15 Second Order Centrality

second_order_centrality(G) Compute the second order centrality for nodes of G.

[Link].second_order_centrality

second_order_centrality(G)
Compute the second order centrality for nodes of G.
The second order centrality of a given node is the standard deviation of the return times to that node of a
perpetual random walk on G:
Parameters G (graph) – A NetworkX connected and undirected graph.
Returns nodes – Dictionary keyed by node with second order centrality as the value.
Return type dictionary
1 Mahendra Piraveenan, Mikhail Prokopenko, Liaquat Hossain Percolation Centrality: Quantifying Graph-Theoretic Impact of Nodes during

Percolation in Networks [Link]


2 Ulrik Brandes: A Faster Algorithm for Betweenness Centrality. Journal of Mathematical Sociology 25(2):163-177, 2001. [Link]

[Link]/algo/publications/[Link]

240 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Examples

>>> G = nx.star_graph(10)
>>> soc = nx.second_order_centrality(G)
>>> print(sorted([Link](), key=lambda x: x[1])[0][0]) # pick first id
0

Raises NetworkXException – If the graph G is empty, non connected or has negative weights.

See also:
betweenness_centrality()

Notes

Lower values of second order centrality indicate higher centrality.


The algorithm is from Kermarrec, Le Merrer, Sericola and Trédan1 .
This code implements the analytical version of the algorithm, i.e., there is no simulation of a random walk
process involved. The random walk is here unbiased (corresponding to eq 6 of the paper1 ), thus the centrality
values are the standard deviations for random walk return times on the transformed input graph G (equal in-
degree at each nodes by adding self-loops).
Complexity of this implementation, made to run locally on a single machine, is O(n^3), with n the size of G,
which makes it viable only for small graphs.

References

3.7.16 Trophic

trophic_levels(G[, weight]) Compute the trophic levels of nodes.


trophic_differences(G[, weight]) Compute the trophic differences of the edges of a di-
rected graph.
trophic_incoherence_parameter(G[, Compute the trophic incoherence parameter of a graph.
weight, . . . ])

[Link].trophic_levels

trophic_levels(G, weight='weight')
Compute the trophic levels of nodes.
The trophic level of a node 𝑖 is
1 ∑︁
𝑠𝑖 = 1 + 𝑎𝑖𝑗 𝑠𝑗
𝑘𝑖𝑖𝑛 𝑗

where 𝑘𝑖𝑖𝑛 is the in-degree of i


∑︁
𝑘𝑖𝑖𝑛 = 𝑎𝑖𝑗
𝑗

1 Anne-Marie Kermarrec, Erwan Le Merrer, Bruno Sericola, Gilles Trédan “Second order centrality: Distributed assessment of nodes criticity
in complex networks”, Elsevier Computer Communications 34(5):619-628, 2011.

3.7. Centrality 241


NetworkX Reference, Release 2.5

and nodes with 𝑘𝑖𝑖𝑛 = 0 have 𝑠𝑖 = 1 by convention.


These are calculated using the method outlined in Levine1 .
Parameters G (DiGraph) – A directed networkx graph
Returns nodes – Dictionary of nodes with trophic level as the vale.
Return type dict

References

[Link].trophic_differences

trophic_differences(G, weight='weight')
Compute the trophic differences of the edges of a directed graph.
The trophic difference 𝑥𝑖 𝑗 for each edge is defined in Johnson et al.1 as:

𝑥𝑖 𝑗 = 𝑠𝑗 − 𝑠𝑖

Where 𝑠𝑖 is the trophic level of node 𝑖.


Parameters G (DiGraph) – A directed networkx graph
Returns diffs – Dictionary of edges with trophic differences as the value.
Return type dict

References

[Link].trophic_incoherence_parameter

trophic_incoherence_parameter(G, weight='weight', cannibalism=False)


Compute the trophic incoherence parameter of a graph.
Trophic coherence is defined as the homogeneity of the distribution of trophic distances: the more similar, the
more coherent. This is measured by the standard deviation of the trophic differences and referred to as the
trophic incoherence parameter 𝑞 by [1].
Parameters
• G (DiGraph) – A directed networkx graph
• cannibalism (Boolean) – If set to False, self edges are not considered in the calculation
Returns trophic_incoherence_parameter – The trophic coherence of a graph
Return type float
1 Stephen Levine (1980) J. theor. Biol. 83, 195-207
1 Samuel Johnson, Virginia Dominguez-Garcia, Luca Donetti, Miguel A. Munoz (2014) PNAS “Trophic coherence determines food-web stabil-
ity”

242 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

References

3.7.17 VoteRank

voterank(G[, number_of_nodes]) Select a list of influential nodes in a graph using VoteR-


ank algorithm

[Link]

voterank(G, number_of_nodes=None)
Select a list of influential nodes in a graph using VoteRank algorithm
VoteRank1 computes a ranking of the nodes in a graph G based on a voting scheme. With VoteRank, all nodes
vote for each of its in-neighbours and the node with the highest votes is elected iteratively. The voting ability of
out-neighbors of elected nodes is decreased in subsequent turns.
Note: We treat each edge independently in case of multigraphs.
Parameters
• G (graph) – A NetworkX graph.
• number_of_nodes (integer, optional) – Number of ranked nodes to extract (default all
nodes).
Returns voterank – Ordered list of computed seeds. Only nodes with positive number of votes are
returned.
Return type list

References

3.8 Chains

Functions for finding chains in a graph.

chain_decomposition(G[, root]) Returns the chain decomposition of a graph.

3.8.1 [Link].chain_decomposition

chain_decomposition(G, root=None)
Returns the chain decomposition of a graph.
The chain decomposition of a graph with respect a depth-first search tree is a set of cycles or paths derived from
the set of fundamental cycles of the tree in the following manner. Consider each fundamental cycle with respect
to the given tree, represented as a list of edges beginning with the nontree edge oriented away from the root of
the tree. For each fundamental cycle, if it overlaps with any previous fundamental cycle, just take the initial
non-overlapping segment, which is a path instead of a cycle. Each cycle or path is called a chain. For more
information, see1 .
1 Zhang, J.-X. et al. (2016). Identifying a set of influential spreaders in complex networks. Sci. Rep. 6, 27823; doi: 10.1038/srep27823.
1 Jens M. Schmidt (2013). “A simple test on 2-vertex- and 2-edge-connectivity.” Information Processing Letters, 113, 241–244. Elsevier.
<[Link]

3.8. Chains 243


NetworkX Reference, Release 2.5

Parameters
• G (undirected graph)
• root (node (optional)) – A node in the graph G. If specified, only the chain decomposition
for the connected component containing this node will be returned. This node indicates the
root of the depth-first search tree.
Yields chain (list) – A list of edges representing a chain. There is no guarantee on the orientation
of the edges in each chain (for example, if a chain includes the edge joining nodes 1 and 2, the
chain may include either (1, 2) or (2, 1)).
Raises NodeNotFound – If root is not in the graph G.

Notes

The worst-case running time of this implementation is linear in the number of nodes and number of edges1 .

References

3.9 Chordal

Algorithms for chordal graphs.


A graph is chordal if every cycle of length at least 4 has a chord (an edge joining two nodes not adjacent in the cycle).
[Link]

is_chordal(G) Checks whether G is a chordal graph.


chordal_graph_cliques(G) Returns the set of maximal cliques of a chordal graph.
chordal_graph_treewidth(G) Returns the treewidth of the chordal graph G.
complete_to_chordal_graph(G) Return a copy of G completed to a chordal graph
find_induced_nodes(G, s, t[, treewidth_bound]) Returns the set of induced nodes in the path from s to t.

3.9.1 [Link].is_chordal

is_chordal(G)
Checks whether G is a chordal graph.
A graph is chordal if every cycle of length at least 4 has a chord (an edge joining two nodes not adjacent in the
cycle).
Parameters G (graph) – A NetworkX graph.
Returns chordal – True if G is a chordal graph and False otherwise.
Return type bool
Raises NetworkXError – The algorithm does not support DiGraph, MultiGraph and MultiDi-
Graph. If the input graph is an instance of one of these classes, a NetworkXError is raised.

244 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Examples

>>> e = [
... (1, 2),
... (1, 3),
... (2, 3),
... (2, 4),
... (3, 4),
... (3, 5),
... (3, 6),
... (4, 5),
... (4, 6),
... (5, 6),
... ]
>>> G = [Link](e)
>>> nx.is_chordal(G)
True

Notes

The routine tries to go through every node following maximum cardinality search. It returns False when it finds
that the separator for any node is not a clique. Based on the algorithms in1 .

References

3.9.2 [Link].chordal_graph_cliques

chordal_graph_cliques(G)
Returns the set of maximal cliques of a chordal graph.
The algorithm breaks the graph in connected components and performs a maximum cardinality search in each
component to get the cliques.
Parameters G (graph) – A NetworkX graph
Returns cliques
Return type A set containing the maximal cliques in G.
Raises NetworkXError – The algorithm does not support DiGraph, MultiGraph and MultiDi-
Graph. If the input graph is an instance of one of these classes, a NetworkXError is raised.
The algorithm can only be applied to chordal graphs. If the input graph is found to be non-
chordal, a NetworkXError is raised.
1 R. E. Tarjan and M. Yannakakis, Simple linear-time algorithms to test chordality of graphs, test acyclicity of hypergraphs, and selectively

reduce acyclic hypergraphs, SIAM J. Comput., 13 (1984), pp. 566–579.

3.9. Chordal 245


NetworkX Reference, Release 2.5

Examples

>>> e = [
... (1, 2),
... (1, 3),
... (2, 3),
... (2, 4),
... (3, 4),
... (3, 5),
... (3, 6),
... (4, 5),
... (4, 6),
... (5, 6),
... (7, 8),
... ]
>>> G = [Link](e)
>>> G.add_node(9)
>>> setlist = nx.chordal_graph_cliques(G)

3.9.3 [Link].chordal_graph_treewidth

chordal_graph_treewidth(G)
Returns the treewidth of the chordal graph G.
Parameters G (graph) – A NetworkX graph
Returns treewidth – The size of the largest clique in the graph minus one.
Return type int
Raises NetworkXError – The algorithm does not support DiGraph, MultiGraph and MultiDi-
Graph. If the input graph is an instance of one of these classes, a NetworkXError is raised.
The algorithm can only be applied to chordal graphs. If the input graph is found to be non-
chordal, a NetworkXError is raised.

Examples

>>> e = [
... (1, 2),
... (1, 3),
... (2, 3),
... (2, 4),
... (3, 4),
... (3, 5),
... (3, 6),
... (4, 5),
... (4, 6),
... (5, 6),
... (7, 8),
... ]
>>> G = [Link](e)
>>> G.add_node(9)
>>> nx.chordal_graph_treewidth(G)
3

246 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

References

3.9.4 [Link].complete_to_chordal_graph

complete_to_chordal_graph(G)
Return a copy of G completed to a chordal graph
Adds edges to a copy of G to create a chordal graph. A graph G=(V,E) is called chordal if for each cycle with
length bigger than 3, there exist two non-adjacent nodes connected by an edge (called a chord).
Parameters G (NetworkX graph) – Undirected graph
Returns
• H (NetworkX graph) – The chordal enhancement of G
• alpha (Dictionary) – The elimination ordering of nodes of G

Notes

There are different approaches to calculate the chordal enhancement of a graph. The algorithm used here is
called MCS-M and gives at least minimal (local) triangulation of graph. Note that this triangulation is not
necessarily a global minimum.
[Link]

References

Examples

>>> from [Link] import complete_to_chordal_graph


>>> G = nx.wheel_graph(10)
>>> H, alpha = complete_to_chordal_graph(G)

3.9.5 [Link].find_induced_nodes

find_induced_nodes(G, s, t, treewidth_bound=9223372036854775807)
Returns the set of induced nodes in the path from s to t.
Parameters
• G (graph) – A chordal NetworkX graph
• s (node) – Source node to look for induced nodes
• t (node) – Destination node to look for induced nodes
• treewith_bound (float) – Maximum treewidth acceptable for the graph H. The search for
induced nodes will end as soon as the treewidth_bound is exceeded.
Returns Induced_nodes – The set of induced nodes in the path from s to t in G
Return type Set of nodes
Raises NetworkXError – The algorithm does not support DiGraph, MultiGraph and MultiDi-
Graph. If the input graph is an instance of one of these classes, a NetworkXError is raised.
The algorithm can only be applied to chordal graphs. If the input graph is found to be non-
chordal, a NetworkXError is raised.

3.9. Chordal 247


NetworkX Reference, Release 2.5

Examples

>>> G = [Link]()
>>> G = [Link].path_graph(10)
>>> induced_nodes = nx.find_induced_nodes(G, 1, 9, 2)
>>> sorted(induced_nodes)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Notes

G must be a chordal graph and (s,t) an edge that is not in G.


If a treewidth_bound is provided, the search for induced nodes will end as soon as the treewidth_bound is
exceeded.
The algorithm is inspired by Algorithm 4 in1 . A formal definition of induced node can also be found on that
reference.

References

3.10 Clique

Functions for finding and manipulating cliques.


Finding the largest clique in a graph is NP-complete problem, so most of these algorithms have an exponential running
time; for more information, see the Wikipedia article on the clique problem1 .

enumerate_all_cliques(G) Returns all cliques in an undirected graph.


find_cliques(G) Returns all maximal cliques in an undirected graph.
make_max_clique_graph(G[, create_using]) Returns the maximal clique graph of the given graph.
make_clique_bipartite(G[, fpos, . . . ]) Returns the bipartite clique graph corresponding to G.
graph_clique_number(G[, cliques]) Returns the clique number of the graph.
graph_number_of_cliques(G[, cliques]) Returns the number of maximal cliques in the graph.
node_clique_number(G[, nodes, cliques]) Returns the size of the largest maximal clique contain-
ing each given node.
number_of_cliques(G[, nodes, cliques]) Returns the number of maximal cliques for each node.
cliques_containing_node(G[, nodes, cliques]) Returns a list of cliques containing the given node.
max_weight_clique(G[, weight]) Find a maximum weight clique in G.
1 Learning Bounded Treewidth Bayesian Networks. Gal Elidan, Stephen Gould; JMLR, 9(Dec):2699–2731, 2008. [Link]

papers/volume9/elidan08a/[Link]
1 clique problem:: [Link]

248 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

3.10.1 [Link].enumerate_all_cliques

enumerate_all_cliques(G)
Returns all cliques in an undirected graph.
This function returns an iterator over cliques, each of which is a list of nodes. The iteration is ordered by
cardinality of the cliques: first all cliques of size one, then all cliques of size two, etc.
Parameters G (NetworkX graph) – An undirected graph.
Returns An iterator over cliques, each of which is a list of nodes in G. The cliques are ordered
according to size.
Return type iterator

Notes

To obtain a list of all cliques, use list(enumerate_all_cliques(G)). However, be aware that in the
worst-case, the length of this list can be exponential in the number of nodes in the graph (for example, when
the graph is the complete graph). This function avoids storing all cliques in memory by only keeping current
candidate node lists in memory during its search.
The implementation is adapted from the algorithm by Zhang, et al. (2005)1 to output all cliques discovered.
This algorithm ignores self-loops and parallel edges, since cliques are not conventionally defined with such
edges.

References

3.10.2 [Link].find_cliques

find_cliques(G)
Returns all maximal cliques in an undirected graph.
For each node v, a maximal clique for v is a largest complete subgraph containing v. The largest maximal clique
is sometimes called the maximum clique.
This function returns an iterator over cliques, each of which is a list of nodes. It is an iterative implementation,
so should not suffer from recursion depth issues.
Parameters G (NetworkX graph) – An undirected graph.
Returns An iterator over maximal cliques, each of which is a list of nodes in G. The order of cliques
is arbitrary.
Return type iterator
See also:

find_cliques_recursive() A recursive version of the same algorithm.


1 Yun Zhang, Abu-Khzam, F.N., Baldwin, N.E., Chesler, E.J., Langston, M.A., Samatova, N.F., “Genome-Scale Computational Approaches to

Memory-Intensive Applications in Systems Biology”. Supercomputing, 2005. Proceedings of the ACM/IEEE SC 2005 Conference, pp. 12, 12–18
Nov. 2005. <[Link]

3.10. Clique 249


NetworkX Reference, Release 2.5

Notes

To obtain a list of all maximal cliques, use list(find_cliques(G)). However, be aware that in the worst-
case, the length of this list can be exponential in the number of nodes in the graph. This function avoids storing
all cliques in memory by only keeping current candidate node lists in memory during its search.
This implementation is based on the algorithm published by Bron and Kerbosch (1973)1 , as adapted by Tomita,
Tanaka and Takahashi (2006)2 and discussed in Cazals and Karande (2008)3 . It essentially unrolls the re-
cursion used in the references to avoid issues of recursion stack depth (for a recursive implementation, see
find_cliques_recursive()).
This algorithm ignores self-loops and parallel edges, since cliques are not conventionally defined with such
edges.

References

3.10.3 [Link].make_max_clique_graph

make_max_clique_graph(G, create_using=None)
Returns the maximal clique graph of the given graph.
The nodes of the maximal clique graph of G are the cliques of G and an edge joins two cliques if the cliques are
not disjoint.
Parameters
• G (NetworkX graph)
• create_using (NetworkX graph constructor, optional (default=[Link])) – Graph type to
create. If graph instance, then cleared before populated.
Returns A graph whose nodes are the cliques of G and whose edges join two cliques if they are not
disjoint.
Return type NetworkX graph

Notes

This function behaves like the following code:

import networkx as nx
G = nx.make_clique_bipartite(G)
cliques = [v for v in [Link]() if [Link][v]['bipartite'] == 0]
G = [Link](G, cliques)
G = nx.relabel_nodes(G, {-v: v - 1 for v in G})

It should be faster, though, since it skips all the intermediate steps.


1 Bron, C. and Kerbosch, J. “Algorithm 457: finding all cliques of an undirected graph”. Communications of the ACM 16, 9 (Sep. 1973),
575–577. <[Link]
2 Etsuji Tomita, Akira Tanaka, Haruhisa Takahashi, “The worst-case time complexity for generating all maximal cliques and computational

experiments”, Theoretical Computer Science, Volume 363, Issue 1, Computing and Combinatorics, 10th Annual International Conference on
Computing and Combinatorics (COCOON 2004), 25 October 2006, Pages 28–42 <[Link]
3 F. Cazals, C. Karande, “A note on the problem of reporting maximal cliques”, Theoretical Computer Science, Volume 407, Issues 1–3, 6

November 2008, Pages 564–568, <[Link]

250 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

3.10.4 [Link].make_clique_bipartite

make_clique_bipartite(G, fpos=None, create_using=None, name=None)


Returns the bipartite clique graph corresponding to G.
In the returned bipartite graph, the “bottom” nodes are the nodes of G and the “top” nodes represent the maximal
cliques of G. There is an edge from node v to clique C in the returned graph if and only if v is an element of C.
Parameters
• G (NetworkX graph) – An undirected graph.
• fpos (bool) – If True or not None, the returned graph will have an additional attribute, pos,
a dictionary mapping node to position in the Euclidean plane.
• create_using (NetworkX graph constructor, optional (default=[Link])) – Graph type to
create. If graph instance, then cleared before populated.
Returns
A bipartite graph whose “bottom” set is the nodes of the graph G, whose “top” set is the cliques
of G, and whose edges join nodes of G to the cliques that contain them.
The nodes of the graph G have the node attribute ‘bipartite’ set to 1 and the nodes representing
cliques have the node attribute ‘bipartite’ set to 0, as is the convention for bipartite graphs in
NetworkX.
Return type NetworkX graph

3.10.5 [Link].graph_clique_number

graph_clique_number(G, cliques=None)
Returns the clique number of the graph.
The clique number of a graph is the size of the largest clique in the graph.
Parameters
• G (NetworkX graph) – An undirected graph.
• cliques (list) – A list of cliques, each of which is itself a list of nodes. If not specified, the
list of all cliques will be computed, as by find_cliques().
Returns The size of the largest clique in G.
Return type int

Notes

You should provide cliques if you have already computed the list of maximal cliques, in order to avoid an
exponential time search for maximal cliques.

3.10. Clique 251


NetworkX Reference, Release 2.5

3.10.6 [Link].graph_number_of_cliques

graph_number_of_cliques(G, cliques=None)
Returns the number of maximal cliques in the graph.
Parameters
• G (NetworkX graph) – An undirected graph.
• cliques (list) – A list of cliques, each of which is itself a list of nodes. If not specified, the
list of all cliques will be computed, as by find_cliques().
Returns The number of maximal cliques in G.
Return type int

Notes

You should provide cliques if you have already computed the list of maximal cliques, in order to avoid an
exponential time search for maximal cliques.

3.10.7 [Link].node_clique_number

node_clique_number(G, nodes=None, cliques=None)


Returns the size of the largest maximal clique containing each given node.
Returns a single or list depending on input nodes. Optional list of cliques can be input if already computed.

3.10.8 [Link].number_of_cliques

number_of_cliques(G, nodes=None, cliques=None)


Returns the number of maximal cliques for each node.
Returns a single or list depending on input nodes. Optional list of cliques can be input if already computed.

3.10.9 [Link].cliques_containing_node

cliques_containing_node(G, nodes=None, cliques=None)


Returns a list of cliques containing the given node.
Returns a single list or list of lists depending on input nodes. Optional list of cliques can be input if already
computed.

3.10.10 [Link].max_weight_clique

max_weight_clique(G, weight='weight')
Find a maximum weight clique in G.
A clique in a graph is a set of nodes such that every two distinct nodes are adjacent. The weight of a clique is
the sum of the weights of its nodes. A maximum weight clique of graph G is a clique C in G such that no clique
in G has weight greater than the weight of C.
Parameters
• G (NetworkX graph) – Undirected graph

252 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

• weight (string or None, optional (default=’weight’)) – The node attribute that holds the
integer value used as a weight. If None, then each node has weight 1.
Returns
• clique (list) – the nodes of a maximum weight clique
• weight (int) – the weight of a maximum weight clique

Notes

The implementation is recursive, and therefore it may run into recursion depth issues if G contains a clique
whose number of nodes is close to the recursion depth limit.
At each search node, the algorithm greedily constructs a weighted independent set cover of part of the graph in
order to find a small set of nodes on which to branch. The algorithm is very similar to the algorithm of Tavares
et al.1 , other than the fact that the NetworkX version does not use bitsets. This style of algorithm for maximum
weight clique (and maximum weight independent set, which is the same problem but on the complement graph)
has a decades-long history. See Algorithm B of Warren and Hicks2 and the references in that paper.

References

3.11 Clustering

Algorithms to characterize the number of triangles in a graph.

triangles(G[, nodes]) Compute the number of triangles.


transitivity(G) Compute graph transitivity, the fraction of all possible
triangles present in G.
clustering(G[, nodes, weight]) Compute the clustering coefficient for nodes.
average_clustering(G[, nodes, weight, . . . ]) Compute the average clustering coefficient for the graph
G.
square_clustering(G[, nodes]) Compute the squares clustering coefficient for nodes.
generalized_degree(G[, nodes]) Compute the generalized degree for nodes.

3.11.1 [Link]

triangles(G, nodes=None)
Compute the number of triangles.
Finds the number of triangles that include a node as one vertex.
Parameters
• G (graph) – A networkx graph
• nodes (container of nodes, optional (default= all nodes in G)) – Compute triangles for nodes
in this container.
Returns out – Number of triangles keyed by node label.
1 Tavares, W.A., Neto, M.B.C., Rodrigues, C.D., Michelon, P.: Um algoritmo de branch and bound para o problema da clique máxima ponderada.

Proceedings of XLVII SBPO 1 (2015).


2 Warrent, Jeffrey S, Hicks, Illya V.: Combinatorial Branch-and-Bound for the Maximum Weight Independent Set Problem. Technical Report,

Texas A&M University (2016).

3.11. Clustering 253


NetworkX Reference, Release 2.5

Return type dictionary

Examples

>>> G = nx.complete_graph(5)
>>> print([Link](G, 0))
6
>>> print([Link](G))
{0: 6, 1: 6, 2: 6, 3: 6, 4: 6}
>>> print(list([Link](G, (0, 1)).values()))
[6, 6]

Notes

When computing triangles for the entire graph each triangle is counted three times, once at each node. Self
loops are ignored.

3.11.2 [Link]

transitivity(G)
Compute graph transitivity, the fraction of all possible triangles present in G.
Possible triangles are identified by the number of “triads” (two edges with a shared vertex).
The transitivity is

#𝑡𝑟𝑖𝑎𝑛𝑔𝑙𝑒𝑠
𝑇 =3 .
#𝑡𝑟𝑖𝑎𝑑𝑠
Parameters G (graph)
Returns out – Transitivity
Return type float

Examples

>>> G = nx.complete_graph(5)
>>> print([Link](G))
1.0

3.11.3 [Link]

clustering(G, nodes=None, weight=None)


Compute the clustering coefficient for nodes.
For unweighted graphs, the clustering of a node 𝑢 is the fraction of possible triangles through that node that
exist,
2𝑇 (𝑢)
𝑐𝑢 = ,
𝑑𝑒𝑔(𝑢)(𝑑𝑒𝑔(𝑢) − 1)

where 𝑇 (𝑢) is the number of triangles through node 𝑢 and 𝑑𝑒𝑔(𝑢) is the degree of 𝑢.

254 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

For weighted graphs, there are several ways to define clustering1 . the one used here is defined as the geometric
average of the subgraph edge weights2 ,
1 ∑︁
𝑐𝑢 = (𝑤
ˆ𝑢𝑣 𝑤 ˆ𝑣𝑤 )1/3 .
ˆ𝑢𝑤 𝑤
𝑑𝑒𝑔(𝑢)(𝑑𝑒𝑔(𝑢) − 1)) 𝑣𝑤

The edge weights 𝑤


ˆ𝑢𝑣 are normalized by the maximum weight in the network 𝑤
ˆ𝑢𝑣 = 𝑤𝑢𝑣 / max(𝑤).
The value of 𝑐𝑢 is assigned to 0 if 𝑑𝑒𝑔(𝑢) < 2.
For directed graphs, the clustering is similarly defined as the fraction of all possible directed triangles or geo-
metric average of the subgraph edge weights for unweighted and weighted directed graph respectively3 .
1
𝑐𝑢 = 𝑇 (𝑢),
𝑑𝑒𝑔 𝑡𝑜𝑡 (𝑢)(𝑑𝑒𝑔 𝑡𝑜𝑡 (𝑢) − 1) − 2𝑑𝑒𝑔 ↔ (𝑢)

where 𝑇 (𝑢) is the number of directed triangles through node 𝑢, 𝑑𝑒𝑔 𝑡𝑜𝑡 (𝑢) is the sum of in degree and out degree
of 𝑢 and 𝑑𝑒𝑔 ↔ (𝑢) is the reciprocal degree of 𝑢.
Parameters
• G (graph)
• nodes (container of nodes, optional (default=all nodes in G)) – Compute clustering for
nodes in this container.
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical value used as a weight. If None, then each edge has weight 1.
Returns out – Clustering coefficient at specified nodes
Return type float, or dictionary

Examples

>>> G = nx.complete_graph(5)
>>> print([Link](G, 0))
1.0
>>> print([Link](G))
{0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0}

Notes

Self loops are ignored.


1 Generalizations of the clustering coefficient to weighted complex networks by J. Saramäki, M. Kivelä, J.-P. Onnela, K. Kaski, and J. Kertész,

Physical Review E, 75 027105 (2007). [Link]


2 Intensity and coherence of motifs in weighted complex networks by J. P. Onnela, J. Saramäki, J. Kertész, and K. Kaski, Physical Review E,

71(6), 065103 (2005).


3 Clustering in complex directed networks by G. Fagiolo, Physical Review E, 76(2), 026107 (2007).

3.11. Clustering 255


NetworkX Reference, Release 2.5

References

3.11.4 [Link].average_clustering

average_clustering(G, nodes=None, weight=None, count_zeros=True)


Compute the average clustering coefficient for the graph G.
The clustering coefficient for the graph is the average,
1 ∑︁
𝐶= 𝑐𝑣 ,
𝑛
𝑣∈𝐺

where 𝑛 is the number of nodes in G.


Parameters
• G (graph)
• nodes (container of nodes, optional (default=all nodes in G)) – Compute average clustering
for nodes in this container.
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical value used as a weight. If None, then each edge has weight 1.
• count_zeros (bool) – If False include only the nodes with nonzero clustering in the average.
Returns avg – Average clustering
Return type float

Examples

>>> G = nx.complete_graph(5)
>>> print(nx.average_clustering(G))
1.0

Notes

This is a space saving routine; it might be faster to use the clustering function to get a list and then take the
average.
Self loops are ignored.

References

3.11.5 [Link].square_clustering

square_clustering(G, nodes=None)
Compute the squares clustering coefficient for nodes.
For each node return the fraction of possible squares that exist at the node1
∑︀𝑘𝑣 ∑︀𝑘𝑣
𝑤=𝑢+1 𝑞𝑣 (𝑢, 𝑤)
𝐶4 (𝑣) = ∑︀𝑘𝑣 ∑︀𝑢=1
𝑘𝑣
,
𝑢=1 𝑤=𝑢+1 [𝑎𝑣 (𝑢, 𝑤) + 𝑞𝑣 (𝑢, 𝑤)]
1 Pedro G. Lind, Marta C. González, and Hans J. Herrmann. 2005 Cycles and clustering in bipartite networks. Physical Review E (72) 056127.

256 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

where 𝑞𝑣 (𝑢, 𝑤) are the number of common neighbors of 𝑢 and 𝑤 other than 𝑣 (ie squares), and 𝑎𝑣 (𝑢, 𝑤) =
(𝑘𝑢 − (1 + 𝑞𝑣 (𝑢, 𝑤) + 𝜃𝑢𝑣 ))(𝑘𝑤 − (1 + 𝑞𝑣 (𝑢, 𝑤) + 𝜃𝑢𝑤 )), where 𝜃𝑢𝑤 = 1 if 𝑢 and 𝑤 are connected and 0
otherwise.
Parameters
• G (graph)
• nodes (container of nodes, optional (default=all nodes in G)) – Compute clustering for
nodes in this container.
Returns c4 – A dictionary keyed by node with the square clustering coefficient value.
Return type dictionary

Examples

>>> G = nx.complete_graph(5)
>>> print(nx.square_clustering(G, 0))
1.0
>>> print(nx.square_clustering(G))
{0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0}

Notes

While 𝐶3 (𝑣) (triangle clustering) gives the probability that two neighbors of node v are connected with each
other, 𝐶4 (𝑣) is the probability that two neighbors of node v share a common neighbor different from v. This
algorithm can be applied to both bipartite and unipartite networks.

References

3.11.6 [Link].generalized_degree

generalized_degree(G, nodes=None)
Compute the generalized degree for nodes.
For each node, the generalized degree shows how many edges of given triangle multiplicity the node is connected
to. The triangle multiplicity of an edge is the number of triangles an edge participates in. The generalized degree
(0) (𝑁 −2) (𝑗)
of node 𝑖 can be written as a vector k𝑖 = (𝑘𝑖 , . . . , 𝑘𝑖 ) where 𝑘𝑖 is the number of edges attached to node
𝑖 that participate in 𝑗 triangles.
Parameters
• G (graph)
• nodes (container of nodes, optional (default=all nodes in G)) – Compute the generalized
degree for nodes in this container.
Returns out – Generalized degree of specified nodes. The Counter is keyed by edge triangle multi-
plicity.
Return type Counter, or dictionary of Counters

3.11. Clustering 257


NetworkX Reference, Release 2.5

Examples

>>> G = nx.complete_graph(5)
>>> print(nx.generalized_degree(G, 0))
Counter({3: 4})
>>> print(nx.generalized_degree(G))
{0: Counter({3: 4}), 1: Counter({3: 4}), 2: Counter({3: 4}), 3: Counter({3: 4}),
˓→4: Counter({3: 4})}

To recover the number of triangles attached to a node:

>>> k1 = nx.generalized_degree(G, 0)
>>> sum([k * v for k, v in [Link]()]) / 2 == [Link](G, 0)
True

Notes

In a network of N nodes, the highest triangle multiplicty an edge can have is N-2.
The return value does not include a zero entry if no edges of a particular triangle multiplicity are present.
The number of triangles node 𝑖 is attached to can be recovered from the generalized degree k𝑖 =
(0) (𝑁 −2) (1) (2) (𝑁 −2)
(𝑘𝑖 , . . . , 𝑘𝑖 ) by (𝑘𝑖 + 2𝑘𝑖 + . . . + (𝑁 − 2)𝑘𝑖 )/2.

References

3.12 Coloring

greedy_color(G[, strategy, interchange]) Color a graph using various strategies of greedy graph
coloring.
equitable_color(G, num_colors) Provides equitable (r + 1)-coloring for nodes of G in O(r
* n^2) time if deg(G) <= r.

3.12.1 [Link].greedy_color

greedy_color(G, strategy='largest_first', interchange=False)


Color a graph using various strategies of greedy graph coloring.
Attempts to color a graph using as few colors as possible, where no neighbours of a node can have same color
as the node itself. The given strategy determines the order in which nodes are colored.
The strategies are described in1 , and smallest-last is based on2 .
Parameters
• G (NetworkX graph)
• strategy (string or function(G, colors)) – A function (or a string representing a function) that
provides the coloring strategy, by returning nodes in the ordering they should be colored. G
1Adrian Kosowski, and Krzysztof Manuszewski, Classical Coloring of Graphs, Graph Colorings, 2-19, 2004. ISBN 0-8218-3458-4.
2David W. Matula, and Leland L. Beck, “Smallest-last ordering and clustering and graph coloring algorithms.” J. ACM 30, 3 (July 1983),
417–427. <[Link]

258 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

is the graph, and colors is a dictionary of the currently assigned colors, keyed by nodes.
The function must return an iterable over all the nodes in G.
If the strategy function is an iterator generator (that is, a function with yield statements),
keep in mind that the colors dictionary will be updated after each yield, since this
function chooses colors greedily.
If strategy is a string, it must be one of the following, each of which represents one of
the built-in strategy functions.
– 'largest_first'
– 'random_sequential'
– 'smallest_last'
– 'independent_set'
– 'connected_sequential_bfs'
– 'connected_sequential_dfs'
– 'connected_sequential' (alias for the previous strategy)
– 'saturation_largest_first'
– 'DSATUR' (alias for the previous strategy)
• interchange (bool) – Will use the color interchange algorithm described by3 if set to True.
Note that saturation_largest_first and independent_set do not work with
interchange. Furthermore, if you use interchange with your own strategy function, you
cannot rely on the values in the colors argument.
Returns
• A dictionary with keys representing nodes and values representing
• corresponding coloring.

Examples

>>> G = nx.cycle_graph(4)
>>> d = [Link].greedy_color(G, strategy="largest_first")
>>> d in [{0: 0, 1: 1, 2: 0, 3: 1}, {0: 1, 1: 0, 2: 1, 3: 0}]
True

Raises NetworkXPointlessConcept – If strategy is saturation_largest_first


or independent_set and interchange is True.
3 Maciej M. Sysło, Marsingh Deo, Janusz S. Kowalik, Discrete Optimization Algorithms with Pascal Programs, 415-424, 1983. ISBN 0-486-

45353-7.

3.12. Coloring 259


NetworkX Reference, Release 2.5

References

3.12.2 [Link].equitable_color

equitable_color(G, num_colors)
Provides equitable (r + 1)-coloring for nodes of G in O(r * n^2) time if deg(G) <= r. The algorithm is described
in1 .
Attempts to color a graph using r colors, where no neighbors of a node can have same color as the node itself
and the number of nodes with each color differ by at most 1.
Parameters
• G (networkX graph) – The nodes of this graph will be colored.
• num_colors (number of colors to use) – This number must be at least one more than the
maximum degree of nodes in the graph.
Returns
• A dictionary with keys representing nodes and values representing
• corresponding coloring.

Examples

>>> G = nx.cycle_graph(4)
>>> d = [Link].equitable_color(G, num_colors=3)
>>> [Link].equitable_coloring.is_equitable(G, d)
True

Raises NetworkXAlgorithmError – If the maximum degree of the graph G is greater than


num_colors.

References

Some node ordering strategies are provided for use with greedy_color().

strategy_connected_sequential(G, colors[, Returns an iterable over nodes in G in the order given by


. . . ]) a breadth-first or depth-first traversal.
strategy_connected_sequential_dfs(G, Returns an iterable over nodes in G in the order given by
colors) a depth-first traversal.
strategy_connected_sequential_bfs(G, Returns an iterable over nodes in G in the order given by
colors) a breadth-first traversal.
strategy_independent_set(G, colors) Uses a greedy independent set removal strategy to de-
termine the colors.
strategy_largest_first(G, colors) Returns a list of the nodes of G in decreasing order by
degree.
strategy_random_sequential(G, colors[, Returns a random permutation of the nodes of G as a
seed]) list.
strategy_saturation_largest_first(G, Iterates over all the nodes of G in “saturation order”
colors) (also known as “DSATUR”).
continues on next page
1Kierstead, H. A., Kostochka, A. V., Mydlarz, M., & Szemerédi, E. (2010). A fast algorithm for equitable coloring. Combinatorica, 30(2),
217-224.

260 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Table 54 – continued from previous page


strategy_smallest_last(G, colors) Returns a deque of the nodes of G, “smallest” last.

3.12.3 [Link].strategy_connected_sequential

strategy_connected_sequential(G, colors, traversal='bfs')


Returns an iterable over nodes in G in the order given by a breadth-first or depth-first traversal.
traversal must be one of the strings 'dfs' or 'bfs', representing depth-first traversal or breadth-first
traversal, respectively.
The generated sequence has the property that for each node except the first, at least one neighbor appeared
earlier in the sequence.
G is a NetworkX graph. colors is ignored.

3.12.4 [Link].strategy_connected_sequential_dfs

strategy_connected_sequential_dfs(G, colors)
Returns an iterable over nodes in G in the order given by a depth-first traversal.
The generated sequence has the property that for each node except the first, at least one neighbor appeared
earlier in the sequence.
G is a NetworkX graph. colors is ignored.

3.12.5 [Link].strategy_connected_sequential_bfs

strategy_connected_sequential_bfs(G, colors)
Returns an iterable over nodes in G in the order given by a breadth-first traversal.
The generated sequence has the property that for each node except the first, at least one neighbor appeared
earlier in the sequence.
G is a NetworkX graph. colors is ignored.

3.12.6 [Link].strategy_independent_set

strategy_independent_set(G, colors)
Uses a greedy independent set removal strategy to determine the colors.
This function updates colors in-place and return None, unlike the other strategy functions in this module.
This algorithm repeatedly finds and removes a maximal independent set, assigning each node in the set an
unused color.
G is a NetworkX graph.
This strategy is related to strategy_smallest_last(): in that strategy, an independent set of size one is
chosen at each step instead of a maximal independent set.

3.12. Coloring 261


NetworkX Reference, Release 2.5

3.12.7 [Link].strategy_largest_first

strategy_largest_first(G, colors)
Returns a list of the nodes of G in decreasing order by degree.
G is a NetworkX graph. colors is ignored.

3.12.8 [Link].strategy_random_sequential

strategy_random_sequential(G, colors, seed=None)


Returns a random permutation of the nodes of G as a list.
G is a NetworkX graph. colors is ignored.
seed [integer, random_state, or None (default)] Indicator of random number generation state. See Randomness.

3.12.9 [Link].strategy_saturation_largest_first

strategy_saturation_largest_first(G, colors)
Iterates over all the nodes of G in “saturation order” (also known as “DSATUR”).
G is a NetworkX graph. colors is a dictionary mapping nodes of G to colors, for those nodes that have already
been colored.

3.12.10 [Link].strategy_smallest_last

strategy_smallest_last(G, colors)
Returns a deque of the nodes of G, “smallest” last.
Specifically, the degrees of each node are tracked in a bucket queue. From this, the node of minimum degree is
repeatedly popped from the graph, updating its neighbors’ degrees.
G is a NetworkX graph. colors is ignored.
This implementation of the strategy runs in 𝑂(𝑛 + 𝑚) time (ignoring polylogarithmic factors), where 𝑛 is the
number of nodes and 𝑚 is the number of edges.
This strategy is related to strategy_independent_set(): if we interpret each node removed as an
independent set of size one, then this strategy chooses an independent set of size one instead of a maximal
independent set.

3.13 Communicability

Communicability.

communicability(G) Returns communicability between all pairs of nodes in


G.
communicability_exp(G) Returns communicability between all pairs of nodes in
G.

262 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

3.13.1 [Link].communicability_alg.communicability

communicability(G)
Returns communicability between all pairs of nodes in G.
The communicability between pairs of nodes in G is the sum of walks of different lengths starting at node u and
ending at node v.
Parameters G (graph)
Returns comm – Dictionary of dictionaries keyed by nodes with communicability as the value.
Return type dictionary of dictionaries
Raises NetworkXError – If the graph is not undirected and simple.
See also:

communicability_exp() Communicability between all pairs of nodes in G using spectral decomposition.


communicability_betweenness_centrality() Communicability betweeness centrality for each
node in G.

Notes

This algorithm uses a spectral decomposition of the adjacency matrix. Let G=(V,E) be a simple undirected
graph. Using the connection between the powers of the adjacency matrix and the number of walks in the graph,
the communicability between nodes u and v based on the graph spectrum is1
𝑛
∑︁
𝐶(𝑢, 𝑣) = 𝜑𝑗 (𝑢)𝜑𝑗 (𝑣)𝑒𝜆𝑗 ,
𝑗=1

where phi_{j}(u) is the urm{th} element of the jrm{th} orthonormal eigenvector of the adjacency
matrix associated with the eigenvalue lambda_{j}.

References

Examples

>>> G = [Link]([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
>>> c = [Link](G)

3.13.2 [Link].communicability_alg.communicability_exp

communicability_exp(G)
Returns communicability between all pairs of nodes in G.
Communicability between pair of node (u,v) of node in G is the sum of walks of different lengths starting at
node u and ending at node v.
Parameters G (graph)
Returns comm – Dictionary of dictionaries keyed by nodes with communicability as the value.
Return type dictionary of dictionaries
1 Ernesto Estrada, Naomichi Hatano, “Communicability in complex networks”, Phys. Rev. E 77, 036111 (2008). [Link]

3.13. Communicability 263


NetworkX Reference, Release 2.5

Raises NetworkXError – If the graph is not undirected and simple.


See also:

communicability() Communicability between pairs of nodes in G.


communicability_betweenness_centrality() Communicability betweeness centrality for each
node in G.

Notes

This algorithm uses matrix exponentiation of the adjacency matrix.


Let G=(V,E) be a simple undirected graph. Using the connection between the powers of the adjacency matrix
and the number of walks in the graph, the communicability between nodes u and v is1 ,

𝐶(𝑢, 𝑣) = (𝑒𝐴 )𝑢𝑣 ,

where A is the adjacency matrix of G.

References

Examples

>>> G = [Link]([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
>>> c = nx.communicability_exp(G)

3.14 Communities

Functions for computing and measuring community structure.


The functions in this class are not imported into the top-level networkx namespace. You can access these functions
by importing the [Link] module, then accessing the functions as attributes of
community. For example:

>>> from [Link] import community


>>> G = nx.barbell_graph(5, 1)
>>> communities_generator = community.girvan_newman(G)
>>> top_level_communities = next(communities_generator)
>>> next_level_communities = next(communities_generator)
>>> sorted(map(sorted, next_level_communities))
[[0, 1, 2, 3, 4], [5], [6, 7, 8, 9, 10]]

1 Ernesto Estrada, Naomichi Hatano, “Communicability in complex networks”, Phys. Rev. E 77, 036111 (2008). [Link]

264 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

3.14.1 Bipartitions

Functions for computing the Kernighan–Lin bipartition algorithm.

kernighan_lin_bisection(G[, partition, . . . ]) Partition a graph into two blocks using the


Kernighan–Lin algorithm.

[Link].kernighan_lin.kernighan_lin_bisection

kernighan_lin_bisection(G, partition=None, max_iter=10, weight='weight', seed=None)


Partition a graph into two blocks using the Kernighan–Lin algorithm.
This algorithm partitions a network into two sets by iteratively swapping pairs of nodes to reduce the edge cut
between the two sets. The pairs are chosen according to a modified form of Kernighan-Lin, which moves node
individually, alternating between sides to keep the bisection balanced.
Parameters
• G (graph)
• partition (tuple) – Pair of iterables containing an initial partition. If not specified, a random
balanced partition is used.
• max_iter (int) – Maximum number of times to attempt swaps to find an improvemement
before giving up.
• weight (key) – Edge data key to use as weight. If None, the weights are all set to one.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness. Only used if partition is None
Returns partition – A pair of sets of nodes representing the bipartition.
Return type tuple
Raises NetworkXError – If partition is not a valid partition of the nodes of the graph.

References

3.14.2 K-Clique

k_clique_communities(G, k[, cliques]) Find k-clique communities in graph using the percola-
tion method.

[Link].k_clique_communities

k_clique_communities(G, k, cliques=None)
Find k-clique communities in graph using the percolation method.
A k-clique community is the union of all cliques of size k that can be reached through adjacent (sharing k-1
nodes) k-cliques.
Parameters
• G (NetworkX graph)
• k (int) – Size of smallest clique

3.14. Communities 265


NetworkX Reference, Release 2.5

• cliques (list or generator) – Precomputed cliques (use networkx.find_cliques(G))


Returns
Return type Yields sets of nodes, one for each k-clique community.

Examples

>>> from [Link] import k_clique_communities


>>> G = nx.complete_graph(5)
>>> K5 = nx.convert_node_labels_to_integers(G, first_label=2)
>>> G.add_edges_from([Link]())
>>> c = list(k_clique_communities(G, 4))
>>> sorted(list(c[0]))
[0, 1, 2, 3, 4, 5, 6]
>>> list(k_clique_communities(G, 6))
[]

References

3.14.3 Modularity-based communities

Functions for detecting communities based on modularity.

greedy_modularity_communities(G[, Find communities in graph using Clauset-Newman-


weight]) Moore greedy modularity maximization.
_naive_greedy_modularity_communities(G) Find communities in graph using the greedy modularity
maximization.

[Link].modularity_max.greedy_modularity_communities

greedy_modularity_communities(G, weight=None)
Find communities in graph using Clauset-Newman-Moore greedy modularity maximization. This method cur-
rently supports the Graph class and does not consider edge weights.
Greedy modularity maximization begins with each node in its own community and joins the pair of communities
that most increases modularity until no such pair exists.
Parameters G (NetworkX graph)
Returns
Return type Yields sets of nodes, one for each community.

266 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Examples

>>> from [Link] import greedy_modularity_communities


>>> G = nx.karate_club_graph()
>>> c = list(greedy_modularity_communities(G))
>>> sorted(c[0])
[8, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]

References

[Link].modularity_max._naive_greedy_modularity_communities

_naive_greedy_modularity_communities(G)
Find communities in graph using the greedy modularity maximization. This implementation is O(n^4), much
slower than alternatives, but it is provided as an easy-to-understand reference implementation.

3.14.4 Tree partitioning

Lukes Algorithm for exact optimal weighted tree partitioning.

lukes_partitioning(G, max_size[, . . . ]) Optimal partitioning of a weighted tree using the Lukes


algorithm.

[Link].lukes_partitioning

lukes_partitioning(G, max_size: int, node_weight=None, edge_weight=None) → list


Optimal partitioning of a weighted tree using the Lukes algorithm.
This algorithm partitions a connected, acyclic graph featuring integer node weights and float edge weights. The
resulting clusters are such that the total weight of the nodes in each cluster does not exceed max_size and that
the weight of the edges that are cut by the partition is minimum. The algorithm is based on LUKES[1].
Parameters
• G (graph)
• max_size (int) – Maximum weight a partition can have in terms of sum of node_weight for
all nodes in the partition
• edge_weight (key) – Edge data key to use as weight. If None, the weights are all set to one.
• node_weight (key) – Node data key to use as weight. If None, the weights are all set to one.
The data must be int.
Returns partition – A list of sets of nodes representing the clusters of the partition.
Return type list
Raises
• NotATree – If G is not a tree.
• TypeError – If any of the values of node_weight is not int.

3.14. Communities 267


NetworkX Reference, Release 2.5

References

3.14.5 Label propagation

Label propagation community detection algorithms.

asyn_lpa_communities(G[, weight, seed]) Returns communities in G as detected by asynchronous


label propagation.
label_propagation_communities(G) Generates community sets determined by label propa-
gation

[Link].label_propagation.asyn_lpa_communities

asyn_lpa_communities(G, weight=None, seed=None)


Returns communities in G as detected by asynchronous label propagation.
The asynchronous label propagation algorithm is described in1 . The algorithm is probabilistic and the found
communities may vary on different executions.
The algorithm proceeds as follows. After initializing each node with a unique label, the algorithm repeatedly sets
the label of a node to be the label that appears most frequently among that nodes neighbors. The algorithm halts
when each node has the label that appears most frequently among its neighbors. The algorithm is asynchronous
because each node is updated without waiting for updates on the remaining nodes.
This generalized version of the algorithm in1 accepts edge weights.
Parameters
• G (Graph)
• weight (string) – The edge attribute representing the weight of an edge. If None, each
edge is assumed to have weight one. In this algorithm, the weight of an edge is used in
determining the frequency with which a label appears among the neighbors of a node: a
higher weight means the label appears more often.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
Returns communities – Iterable of communities given as sets of nodes.
Return type iterable

Notes

Edge weight attributes must be numerical.


1 Raghavan, Usha Nandini, Réka Albert, and Soundar Kumara. “Near linear time algorithm to detect community structures in large-scale

networks.” Physical Review E 76.3 (2007): 036106.

268 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

References

[Link].label_propagation.label_propagation_communities

label_propagation_communities(G)
Generates community sets determined by label propagation
Finds communities in G using a semi-synchronous label propagation method[1]_. This method combines the
advantages of both the synchronous and asynchronous models. Not implemented for directed graphs.
Parameters G (graph) – An undirected NetworkX graph.
Yields communities (generator) – Yields sets of the nodes in each community.
Raises NetworkXNotImplemented – If the graph is directed

References

3.14.6 Fluid Communities

Asynchronous Fluid Communities algorithm for community detection.

asyn_fluidc(G, k[, max_iter, seed]) Returns communities in G as detected by Fluid Commu-


nities algorithm.

[Link].asyn_fluid.asyn_fluidc

asyn_fluidc(G, k, max_iter=100, seed=None)


Returns communities in G as detected by Fluid Communities algorithm.
The asynchronous fluid communities algorithm is described in1 . The algorithm is based on the simple idea of
fluids interacting in an environment, expanding and pushing each other. Its initialization is random, so found
communities may vary on different executions.
The algorithm proceeds as follows. First each of the initial k communities is initialized in a random vertex in the
graph. Then the algorithm iterates over all vertices in a random order, updating the community of each vertex
based on its own community and the communities of its neighbours. This process is performed several times
until convergence. At all times, each community has a total density of 1, which is equally distributed among
the vertices it contains. If a vertex changes of community, vertex densities of affected communities are adjusted
immediately. When a complete iteration over all vertices is done, such that no vertex changes the community it
belongs to, the algorithm has converged and returns.
This is the original version of the algorithm described in1 . Unfortunately, it does not support weighted graphs
yet.
Parameters
• G (Graph)
• k (integer) – The number of communities to be found.
• max_iter (integer) – The number of maximum iterations allowed. By default 100.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
1 Parés F., Garcia-Gasulla D. et al. “Fluid Communities: A Competitive and Highly Scalable Community Detection Algorithm”. [https:
//[Link]/pdf/[Link]].

3.14. Communities 269


NetworkX Reference, Release 2.5

Returns communities – Iterable of communities given as sets of nodes.


Return type iterable

Notes

k variable is not an optional argument.

References

3.14.7 Measuring partitions

Functions for measuring the quality of a partition (into communities).

coverage(G, partition) Returns the coverage of a partition.


modularity(G, communities[, weight]) Returns the modularity of the given partition of the
graph.
performance(G, partition) Returns the performance of a partition.

[Link]

coverage(G, partition)
Returns the coverage of a partition.
The coverage of a partition is the ratio of the number of intra-community edges to the total number of edges in
the graph.
Parameters
• G (NetworkX graph)
• partition (sequence) – Partition of the nodes of G, represented as a sequence of sets of
nodes. Each block of the partition represents a community.
Returns The coverage of the partition, as defined above.
Return type float
Raises NetworkXError – If partition is not a valid partition of the nodes of G.

Notes

If G is a multigraph, the multiplicity of edges is counted.

270 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

References

[Link]

modularity(G, communities, weight='weight')


Returns the modularity of the given partition of the graph.
Modularity is defined in1 as
(︂ )︂
1 ∑︁ 𝑘𝑖 𝑘𝑗
𝑄= 𝐴𝑖𝑗 − 𝛿(𝑐𝑖 , 𝑐𝑗 )
2𝑚 𝑖𝑗 2𝑚

where 𝑚 is the number of edges, 𝐴 is the adjacency matrix of G, 𝑘𝑖 is the degree of 𝑖 and 𝛿(𝑐𝑖 , 𝑐𝑗 ) is 1 if 𝑖 and 𝑗
are in the same community and 0 otherwise.
According to2 (and verified by some algebra) this can be reduced to
𝑛
[︃ (︂ )︂2 ]︃
∑︁ 𝐿𝑐 𝑘𝑐
𝑄= −
𝑐=1
𝑚 2𝑚

where the sum iterates over all communities 𝑐, 𝑚 is the number of edges, 𝐿𝑐 is the number of intra-community
links for community 𝑐, 𝑘𝑐 is the sum of degrees of the nodes in community 𝑐.
The second formula is the one actually used in calculation of the modularity.
Parameters
• G (NetworkX Graph)
• communities (list or iterable of set of nodes) – These node sets must represent a partition
of G’s nodes.
• weight (string or None, optional (default=”weight”)) – The edge attribute that holds the
numerical value used as a weight. If None or an edge does not have that attribute, then that
edge has weight 1.
Returns Q – The modularity of the paritition.
Return type float
Raises NotAPartition – If communities is not a partition of the nodes of G.

Examples

>>> import [Link] as nx_comm


>>> G = nx.barbell_graph(3, 0)
>>> nx_comm.modularity(G, [{0, 1, 2}, {3, 4, 5}])
0.35714285714285715
>>> nx_comm.modularity(G, nx_comm.label_propagation_communities(G))
0.35714285714285715

1M. E. J. Newman Networks: An Introduction, page 224. Oxford University Press, 2011.
2Clauset, Aaron, Mark EJ Newman, and Cristopher Moore. “Finding community structure in very large networks.” Physical review E 70.6
(2004). <[Link]

3.14. Communities 271


NetworkX Reference, Release 2.5

References

[Link]

performance(G, partition)
Returns the performance of a partition.
The performance of a partition is the ratio of the number of intra-community edges plus inter-community non-
edges with the total number of potential edges.
Parameters
• G (NetworkX graph) – A simple graph (directed or undirected).
• partition (sequence) – Partition of the nodes of G, represented as a sequence of sets of
nodes. Each block of the partition represents a community.
Returns The performance of the partition, as defined above.
Return type float
Raises NetworkXError – If partition is not a valid partition of the nodes of G.

References

3.14.8 Partitions via centrality measures

Functions for computing communities based on centrality notions.

girvan_newman(G[, most_valuable_edge]) Finds communities in a graph using the Gir-


van–Newman method.

[Link].girvan_newman

girvan_newman(G, most_valuable_edge=None)
Finds communities in a graph using the Girvan–Newman method.
Parameters
• G (NetworkX graph)
• most_valuable_edge (function) – Function that takes a graph as input and outputs an edge.
The edge returned by this function will be recomputed and removed at each iteration of the
algorithm.
If not specified, the edge with the highest networkx.
edge_betweenness_centrality() will be used.
Returns Iterator over tuples of sets of nodes in G. Each set of node is a community, each tuple is a
sequence of communities at a particular level of the algorithm.
Return type iterator

272 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Examples

To get the first pair of communities:


>>> G = nx.path_graph(10)
>>> comp = girvan_newman(G)
>>> tuple(sorted(c) for c in next(comp))
([0, 1, 2, 3, 4], [5, 6, 7, 8, 9])

To get only the first k tuples of communities, use [Link]():


>>> import itertools
>>> G = nx.path_graph(8)
>>> k = 2
>>> comp = girvan_newman(G)
>>> for communities in [Link](comp, k):
... print(tuple(sorted(c) for c in communities))
...
([0, 1, 2, 3], [4, 5, 6, 7])
([0, 1], [2, 3], [4, 5, 6, 7])

To stop getting tuples of communities once the number of communities is greater than k, use itertools.
takewhile():
>>> import itertools
>>> G = nx.path_graph(8)
>>> k = 4
>>> comp = girvan_newman(G)
>>> limited = [Link](lambda c: len(c) <= k, comp)
>>> for communities in limited:
... print(tuple(sorted(c) for c in communities))
...
([0, 1, 2, 3], [4, 5, 6, 7])
([0, 1], [2, 3], [4, 5, 6, 7])
([0, 1], [2, 3], [4, 5], [6, 7])

To just choose an edge to remove based on the weight:


>>> from operator import itemgetter
>>> G = nx.path_graph(10)
>>> edges = [Link]()
>>> nx.set_edge_attributes(G, {(u, v): v for u, v in edges}, "weight")
>>> def heaviest(G):
... u, v, w = max([Link](data="weight"), key=itemgetter(2))
... return (u, v)
...
>>> comp = girvan_newman(G, most_valuable_edge=heaviest)
>>> tuple(sorted(c) for c in next(comp))
([0, 1, 2, 3, 4, 5, 6, 7, 8], [9])

To utilize edge weights when choosing an edge with, for example, the highest betweenness centrality:
>>> from networkx import edge_betweenness_centrality as betweenness
>>> def most_central_edge(G):
... centrality = betweenness(G, weight="weight")
... return max(centrality, key=[Link])
...
>>> G = nx.path_graph(10)
(continues on next page)

3.14. Communities 273


NetworkX Reference, Release 2.5

(continued from previous page)


>>> comp = girvan_newman(G, most_valuable_edge=most_central_edge)
>>> tuple(sorted(c) for c in next(comp))
([0, 1, 2, 3, 4], [5, 6, 7, 8, 9])

To specify a different ranking algorithm for edges, use the most_valuable_edge keyword argument:

>>> from networkx import edge_betweenness_centrality


>>> from random import random
>>> def most_central_edge(G):
... centrality = edge_betweenness_centrality(G)
... max_cent = max([Link]())
... # Scale the centrality values so they are between 0 and 1,
... # and add some random noise.
... centrality = {e: c / max_cent for e, c in [Link]()}
... # Add some random noise.
... centrality = {e: c + random() for e, c in [Link]()}
... return max(centrality, key=[Link])
...
>>> G = nx.path_graph(10)
>>> comp = girvan_newman(G, most_valuable_edge=most_central_edge)

Notes

The Girvan–Newman algorithm detects communities by progressively removing edges from the original graph.
The algorithm removes the “most valuable” edge, traditionally the edge with the highest betweenness centrality,
at each step. As the graph breaks down into pieces, the tightly knit community structure is exposed and the
result can be depicted as a dendrogram.

3.14.9 Validating partitions

Helper functions for community-finding algorithms.

is_partition(G, communities) Returns True if communities is a partition of the


nodes of G.

[Link].community_utils.is_partition

is_partition(G, communities)
Returns True if communities is a partition of the nodes of G.
A partition of a universe set is a family of pairwise disjoint sets whose union is the entire universe set.
Parameters
• G (NetworkX graph.)
• communities (list or iterable of sets of nodes) – If not a list, the iterable is converted inter-
nally to a list. If it is an iterator it is exhausted.

274 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

3.15 Components

3.15.1 Connectivity

is_connected(G) Returns True if the graph is connected, False otherwise.


number_connected_components(G) Returns the number of connected components.
connected_components(G) Generate connected components.
node_connected_component(G, n) Returns the set of nodes in the component of graph con-
taining node n.

[Link].is_connected

is_connected(G)
Returns True if the graph is connected, False otherwise.
Parameters G (NetworkX Graph) – An undirected graph.
Returns connected – True if the graph is connected, false otherwise.
Return type bool
Raises NetworkXNotImplemented – If G is directed.

Examples

>>> G = nx.path_graph(4)
>>> print(nx.is_connected(G))
True

See also:
is_strongly_connected(), is_weakly_connected(), is_semiconnected(),
is_biconnected(), connected_components()

Notes

For undirected graphs only.

[Link].number_connected_components

number_connected_components(G)
Returns the number of connected components.
Parameters G (NetworkX graph) – An undirected graph.
Returns n – Number of connected components
Return type integer
See also:
connected_components(), number_weakly_connected_components(),
number_strongly_connected_components()

3.15. Components 275


NetworkX Reference, Release 2.5

Notes

For undirected graphs only.

[Link].connected_components

connected_components(G)
Generate connected components.
Parameters G (NetworkX graph) – An undirected graph
Returns comp – A generator of sets of nodes, one for each component of G.
Return type generator of sets
Raises NetworkXNotImplemented – If G is directed.

Examples

Generate a sorted list of connected components, largest first.

>>> G = nx.path_graph(4)
>>> nx.add_path(G, [10, 11, 12])
>>> [len(c) for c in sorted(nx.connected_components(G), key=len, reverse=True)]
[4, 3]

If you only want the largest connected component, it’s more efficient to use max instead of sort.

>>> largest_cc = max(nx.connected_components(G), key=len)

To create the induced subgraph of each component use:

>>> S = [[Link](c).copy() for c in nx.connected_components(G)]

See also:
strongly_connected_components(), weakly_connected_components()

Notes

For undirected graphs only.

[Link].node_connected_component

node_connected_component(G, n)
Returns the set of nodes in the component of graph containing node n.
Parameters
• G (NetworkX Graph) – An undirected graph.
• n (node label) – A node in G
Returns comp – A set of nodes in the component of G containing node n.
Return type set
Raises NetworkXNotImplemented – If G is directed.

276 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

See also:
connected_components()

Notes

For undirected graphs only.

3.15.2 Strong connectivity

is_strongly_connected(G) Test directed graph for strong connectivity.


number_strongly_connected_components(G) Returns number of strongly connected components in
graph.
strongly_connected_components(G) Generate nodes in strongly connected components of
graph.
Generate nodes in strongly connected components
strongly_connected_components_recursive(G) of
graph.
Generate nodes in strongly connected components
kosaraju_strongly_connected_components(G[, of
. . . ]) graph.
condensation(G[, scc]) Returns the condensation of G.

[Link].is_strongly_connected

is_strongly_connected(G)
Test directed graph for strong connectivity.
A directed graph is strongly connected if and only if every vertex in the graph is reachable from every other
vertex.
Parameters G (NetworkX Graph) – A directed graph.
Returns connected – True if the graph is strongly connected, False otherwise.
Return type bool
Raises NetworkXNotImplemented – If G is undirected.
See also:
is_weakly_connected(), is_semiconnected(), is_connected(), is_biconnected(),
strongly_connected_components()

Notes

For directed graphs only.

3.15. Components 277


NetworkX Reference, Release 2.5

[Link].number_strongly_connected_components

number_strongly_connected_components(G)
Returns number of strongly connected components in graph.
Parameters G (NetworkX graph) – A directed graph.
Returns n – Number of strongly connected components
Return type integer
Raises NetworkXNotImplemented – If G is undirected.
See also:
strongly_connected_components(), number_connected_components(),
number_weakly_connected_components()

Notes

For directed graphs only.

[Link].strongly_connected_components

strongly_connected_components(G)
Generate nodes in strongly connected components of graph.
Parameters G (NetworkX Graph) – A directed graph.
Returns comp – A generator of sets of nodes, one for each strongly connected component of G.
Return type generator of sets
Raises NetworkXNotImplemented – If G is undirected.

Examples

Generate a sorted list of strongly connected components, largest first.

>>> G = nx.cycle_graph(4, create_using=[Link]())


>>> nx.add_cycle(G, [10, 11, 12])
>>> [
... len(c)
... for c in sorted(nx.strongly_connected_components(G), key=len,
˓→reverse=True)

... ]
[4, 3]

If you only want the largest component, it’s more efficient to use max instead of sort.

>>> largest = max(nx.strongly_connected_components(G), key=len)

See also:
connected_components(), weakly_connected_components(),
kosaraju_strongly_connected_components()

278 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Notes

Uses Tarjan’s algorithm[1]_ with Nuutila’s modifications[2]_. Nonrecursive version of algorithm.

References

[Link].strongly_connected_components_recursive

strongly_connected_components_recursive(G)
Generate nodes in strongly connected components of graph.
Recursive version of algorithm.
Parameters G (NetworkX Graph) – A directed graph.
Returns comp – A generator of sets of nodes, one for each strongly connected component of G.
Return type generator of sets
Raises NetworkXNotImplemented – If G is undirected.

Examples

Generate a sorted list of strongly connected components, largest first.

>>> G = nx.cycle_graph(4, create_using=[Link]())


>>> nx.add_cycle(G, [10, 11, 12])
>>> [
... len(c)
... for c in sorted(
... nx.strongly_connected_components_recursive(G), key=len, reverse=True
... )
... ]
[4, 3]

If you only want the largest component, it’s more efficient to use max instead of sort.

>>> largest = max(nx.strongly_connected_components_recursive(G), key=len)

To create the induced subgraph of the components use: >>> S = [[Link](c).copy() for c in
nx.weakly_connected_components(G)]
See also:
connected_components()

Notes

Uses Tarjan’s algorithm[1]_ with Nuutila’s modifications[2]_.

3.15. Components 279


NetworkX Reference, Release 2.5

References

[Link].kosaraju_strongly_connected_components

kosaraju_strongly_connected_components(G, source=None)
Generate nodes in strongly connected components of graph.
Parameters G (NetworkX Graph) – A directed graph.
Returns comp – A genrator of sets of nodes, one for each strongly connected component of G.
Return type generator of sets
Raises NetworkXNotImplemented – If G is undirected.

Examples

Generate a sorted list of strongly connected components, largest first.

>>> G = nx.cycle_graph(4, create_using=[Link]())


>>> nx.add_cycle(G, [10, 11, 12])
>>> [
... len(c)
... for c in sorted(
... nx.kosaraju_strongly_connected_components(G), key=len, reverse=True
... )
... ]
[4, 3]

If you only want the largest component, it’s more efficient to use max instead of sort.

>>> largest = max(nx.kosaraju_strongly_connected_components(G), key=len)

See also:
strongly_connected_components()

Notes

Uses Kosaraju’s algorithm.

[Link]

condensation(G, scc=None)
Returns the condensation of G.
The condensation of G is the graph with each of the strongly connected components contracted into a single
node.
Parameters
• G (NetworkX DiGraph) – A directed graph.
• scc (list or generator (optional, default=None)) – Strongly connected components. If pro-
vided, the elements in scc must partition the nodes in G. If not provided, it will be calculated
as scc=nx.strongly_connected_components(G).

280 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Returns C – The condensation graph C of G. The node labels are integers corresponding to the index
of the component in the list of strongly connected components of G. C has a graph attribute
named ‘mapping’ with a dictionary mapping the original nodes to the nodes in C to which they
belong. Each node in C also has a node attribute ‘members’ with the set of original nodes in G
that form the SCC that the node in C represents.
Return type NetworkX DiGraph
Raises NetworkXNotImplemented – If G is undirected.

Notes

After contracting all strongly connected components to a single node, the resulting graph is a directed acyclic
graph.

3.15.3 Weak connectivity

is_weakly_connected(G) Test directed graph for weak connectivity.


number_weakly_connected_components(G) Returns the number of weakly connected components in
G.
weakly_connected_components(G) Generate weakly connected components of G.

[Link].is_weakly_connected

is_weakly_connected(G)
Test directed graph for weak connectivity.
A directed graph is weakly connected if and only if the graph is connected when the direction of the edge
between nodes is ignored.
Note that if a graph is strongly connected (i.e. the graph is connected even when we account for directionality),
it is by definition weakly connected as well.
Parameters G (NetworkX Graph) – A directed graph.
Returns connected – True if the graph is weakly connected, False otherwise.
Return type bool
Raises NetworkXNotImplemented – If G is undirected.
See also:
is_strongly_connected(), is_semiconnected(), is_connected(), is_biconnected(),
weakly_connected_components()

3.15. Components 281


NetworkX Reference, Release 2.5

Notes

For directed graphs only.

[Link].number_weakly_connected_components

number_weakly_connected_components(G)
Returns the number of weakly connected components in G.
Parameters G (NetworkX graph) – A directed graph.
Returns n – Number of weakly connected components
Return type integer
Raises NetworkXNotImplemented – If G is undirected.
See also:
weakly_connected_components(), number_connected_components(),
number_strongly_connected_components()

Notes

For directed graphs only.

[Link].weakly_connected_components

weakly_connected_components(G)
Generate weakly connected components of G.
Parameters G (NetworkX graph) – A directed graph
Returns comp – A generator of sets of nodes, one for each weakly connected component of G.
Return type generator of sets
Raises NetworkXNotImplemented – If G is undirected.

Examples

Generate a sorted list of weakly connected components, largest first.

>>> G = nx.path_graph(4, create_using=[Link]())


>>> nx.add_path(G, [10, 11, 12])
>>> [
... len(c)
... for c in sorted(nx.weakly_connected_components(G), key=len, reverse=True)
... ]
[4, 3]

If you only want the largest component, it’s more efficient to use max instead of sort:

>>> largest_cc = max(nx.weakly_connected_components(G), key=len)

See also:
connected_components(), strongly_connected_components()

282 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Notes

For directed graphs only.

3.15.4 Attracting components

is_attracting_component(G) Returns True if G consists of a single attracting compo-


nent.
number_attracting_components(G) Returns the number of attracting components in G.
attracting_components(G) Generates the attracting components in G.

[Link].is_attracting_component

is_attracting_component(G)
Returns True if G consists of a single attracting component.
Parameters G (DiGraph, MultiDiGraph) – The graph to be analyzed.
Returns attracting – True if G has a single attracting component. Otherwise, False.
Return type bool
Raises NetworkXNotImplemented – If the input graph is undirected.
See also:
attracting_components(), number_attracting_components()

[Link].number_attracting_components

number_attracting_components(G)
Returns the number of attracting components in G.
Parameters G (DiGraph, MultiDiGraph) – The graph to be analyzed.
Returns n – The number of attracting components in G.
Return type int
Raises NetworkXNotImplemented – If the input graph is undirected.
See also:
attracting_components(), is_attracting_component()

[Link].attracting_components

attracting_components(G)
Generates the attracting components in G.
An attracting component in a directed graph G is a strongly connected component with the property that a
random walker on the graph will never leave the component, once it enters the component.
The nodes in attracting components can also be thought of as recurrent nodes. If a random walker enters the
attractor containing the node, then the node will be visited infinitely often.

3.15. Components 283


NetworkX Reference, Release 2.5

To obtain induced subgraphs on each component use: ([Link](c).copy() for c in


attracting_components(G))
Parameters G (DiGraph, MultiDiGraph) – The graph to be analyzed.
Returns attractors – A generator of sets of nodes, one for each attracting component of G.
Return type generator of sets
Raises NetworkXNotImplemented – If the input graph is undirected.
See also:
number_attracting_components(), is_attracting_component()

3.15.5 Biconnected components

is_biconnected(G) Returns True if the graph is biconnected, False other-


wise.
biconnected_components(G) Returns a generator of sets of nodes, one set for each
biconnected component of the graph
biconnected_component_edges(G) Returns a generator of lists of edges, one list for each
biconnected component of the input graph.
articulation_points(G) Yield the articulation points, or cut vertices, of a graph.

[Link].is_biconnected

is_biconnected(G)
Returns True if the graph is biconnected, False otherwise.
A graph is biconnected if, and only if, it cannot be disconnected by removing only one node (and all edges
incident on that node). If removing a node increases the number of disconnected components in the graph, that
node is called an articulation point, or cut vertex. A biconnected graph has no articulation points.
Parameters G (NetworkX Graph) – An undirected graph.
Returns biconnected – True if the graph is biconnected, False otherwise.
Return type bool
Raises NetworkXNotImplemented – If the input graph is not undirected.

Examples

>>> G = nx.path_graph(4)
>>> print(nx.is_biconnected(G))
False
>>> G.add_edge(0, 3)
>>> print(nx.is_biconnected(G))
True

See also:
biconnected_components(), articulation_points(), biconnected_component_edges(),
is_strongly_connected(), is_weakly_connected(), is_connected(),
is_semiconnected()

284 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Notes

The algorithm to find articulation points and biconnected components is implemented using a non-recursive
depth-first-search (DFS) that keeps track of the highest level that back edges reach in the DFS tree. A node n
is an articulation point if, and only if, there exists a subtree rooted at n such that there is no back edge from
any successor of n that links to a predecessor of n in the DFS tree. By keeping track of all the edges traversed
by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed
consecutively between articulation points.

References

[Link].biconnected_components

biconnected_components(G)
Returns a generator of sets of nodes, one set for each biconnected component of the graph
Biconnected components are maximal subgraphs such that the removal of a node (and all edges incident on that
node) will not disconnect the subgraph. Note that nodes may be part of more than one biconnected component.
Those nodes are articulation points, or cut vertices. The removal of articulation points will increase the number
of connected components of the graph.
Notice that by convention a dyad is considered a biconnected component.
Parameters G (NetworkX Graph) – An undirected graph.
Returns nodes – Generator of sets of nodes, one set for each biconnected component.
Return type generator
Raises NetworkXNotImplemented – If the input graph is not undirected.
See also:

k_components() this function is a special case where k=2


bridge_components() similar to this function, but is defined using 2-edge-connectivity instead of 2-node-
connectivity.

Examples

>>> G = nx.lollipop_graph(5, 1)
>>> print(nx.is_biconnected(G))
False
>>> bicomponents = list(nx.biconnected_components(G))
>>> len(bicomponents)
2
>>> G.add_edge(0, 5)
>>> print(nx.is_biconnected(G))
True
>>> bicomponents = list(nx.biconnected_components(G))
>>> len(bicomponents)
1

You can generate a sorted list of biconnected components, largest first, using sort.

3.15. Components 285


NetworkX Reference, Release 2.5

>>> G.remove_edge(0, 5)
>>> [len(c) for c in sorted(nx.biconnected_components(G), key=len, reverse=True)]
[5, 2]

If you only want the largest connected component, it’s more efficient to use max instead of sort.

>>> Gc = max(nx.biconnected_components(G), key=len)

To create the components as subgraphs use: ([Link](c).copy() for c in


biconnected_components(G))
See also:
is_biconnected(), articulation_points(), biconnected_component_edges()

Notes

The algorithm to find articulation points and biconnected components is implemented using a non-recursive
depth-first-search (DFS) that keeps track of the highest level that back edges reach in the DFS tree. A node n
is an articulation point if, and only if, there exists a subtree rooted at n such that there is no back edge from
any successor of n that links to a predecessor of n in the DFS tree. By keeping track of all the edges traversed
by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed
consecutively between articulation points.

References

[Link].biconnected_component_edges

biconnected_component_edges(G)
Returns a generator of lists of edges, one list for each biconnected component of the input graph.
Biconnected components are maximal subgraphs such that the removal of a node (and all edges incident on that
node) will not disconnect the subgraph. Note that nodes may be part of more than one biconnected compo-
nent. Those nodes are articulation points, or cut vertices. However, each edge belongs to one, and only one,
biconnected component.
Notice that by convention a dyad is considered a biconnected component.
Parameters G (NetworkX Graph) – An undirected graph.
Returns edges – Generator of lists of edges, one list for each bicomponent.
Return type generator of lists
Raises NetworkXNotImplemented – If the input graph is not undirected.

286 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Examples

>>> G = nx.barbell_graph(4, 2)
>>> print(nx.is_biconnected(G))
False
>>> bicomponents_edges = list(nx.biconnected_component_edges(G))
>>> len(bicomponents_edges)
5
>>> G.add_edge(2, 8)
>>> print(nx.is_biconnected(G))
True
>>> bicomponents_edges = list(nx.biconnected_component_edges(G))
>>> len(bicomponents_edges)
1

See also:
is_biconnected(), biconnected_components(), articulation_points()

Notes

The algorithm to find articulation points and biconnected components is implemented using a non-recursive
depth-first-search (DFS) that keeps track of the highest level that back edges reach in the DFS tree. A node n
is an articulation point if, and only if, there exists a subtree rooted at n such that there is no back edge from
any successor of n that links to a predecessor of n in the DFS tree. By keeping track of all the edges traversed
by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed
consecutively between articulation points.

References

[Link].articulation_points

articulation_points(G)
Yield the articulation points, or cut vertices, of a graph.
An articulation point or cut vertex is any node whose removal (along with all its incident edges) increases the
number of connected components of a graph. An undirected connected graph without articulation points is
biconnected. Articulation points belong to more than one biconnected component of a graph.
Notice that by convention a dyad is considered a biconnected component.
Parameters G (NetworkX Graph) – An undirected graph.
Yields node – An articulation point in the graph.
Raises NetworkXNotImplemented – If the input graph is not undirected.

3.15. Components 287


NetworkX Reference, Release 2.5

Examples

>>> G = nx.barbell_graph(4, 2)
>>> print(nx.is_biconnected(G))
False
>>> len(list(nx.articulation_points(G)))
4
>>> G.add_edge(2, 8)
>>> print(nx.is_biconnected(G))
True
>>> len(list(nx.articulation_points(G)))
0

See also:
is_biconnected(), biconnected_components(), biconnected_component_edges()

Notes

The algorithm to find articulation points and biconnected components is implemented using a non-recursive
depth-first-search (DFS) that keeps track of the highest level that back edges reach in the DFS tree. A node n
is an articulation point if, and only if, there exists a subtree rooted at n such that there is no back edge from
any successor of n that links to a predecessor of n in the DFS tree. By keeping track of all the edges traversed
by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed
consecutively between articulation points.

References

3.15.6 Semiconnectedness

is_semiconnected(G[, topo_order]) Returns True if the graph is semiconnected, False other-


wise.

[Link].is_semiconnected

is_semiconnected(G, topo_order=None)
Returns True if the graph is semiconnected, False otherwise.
A graph is semiconnected if, and only if, for any pair of nodes, either one is reachable from the other, or they
are mutually reachable.
Parameters
• G (NetworkX graph) – A directed graph.
• topo_order (list or tuple, optional) – A topological order for G (if None, the function will
compute one)
Returns semiconnected – True if the graph is semiconnected, False otherwise.
Return type bool
Raises
• NetworkXNotImplemented – If the input graph is undirected.

288 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

• NetworkXPointlessConcept – If the graph is empty.

Examples

>>> G = nx.path_graph(4, create_using=[Link]())


>>> print(nx.is_semiconnected(G))
True
>>> G = [Link]([(1, 2), (3, 2)])
>>> print(nx.is_semiconnected(G))
False

See also:
is_strongly_connected(), is_weakly_connected(), is_connected(),
is_biconnected()

3.16 Connectivity

Connectivity and cut algorithms

3.16.1 Edge-augmentation

Algorithms for finding k-edge-augmentations


A k-edge-augmentation is a set of edges, that once added to a graph, ensures that the graph is k-edge-connected; i.e.
the graph cannot be disconnected unless k or more edges are removed. Typically, the goal is to find the augmentation
with minimum weight. In general, it is not guaranteed that a k-edge-augmentation exists.
See also:
edge_kcomponents algorithms for finding k-edge-connected components
connectivity algorithms for determening edge connectivity.

k_edge_augmentation(G, k[, avail, weight, . . . ]) Finds set of edges to k-edge-connect G.


is_k_edge_connected(G, k) Tests to see if a graph is k-edge-connected.
is_locally_k_edge_connected(G, s, t, k) Tests to see if an edge in a graph is locally k-edge-
connected.

[Link].edge_augmentation.k_edge_augmentation

k_edge_augmentation(G, k, avail=None, weight=None, partial=False)


Finds set of edges to k-edge-connect G.
Adding edges from the augmentation to G make it impossible to disconnect G unless k or more edges are
removed. This function uses the most efficient function available (depending on the value of k and if the problem
is weighted or unweighted) to search for a minimum weight subset of available edges that k-edge-connects G. In
general, finding a k-edge-augmentation is NP-hard, so solutions are not garuenteed to be minimal. Furthermore,
a k-edge-augmentation may not exist.
Parameters
• G (NetworkX graph) – An undirected graph.

3.16. Connectivity 289


NetworkX Reference, Release 2.5

• k (integer) – Desired edge connectivity


• avail (dict or a set of 2 or 3 tuples) – The available edges that can be used in the augmenta-
tion.
If unspecified, then all edges in the complement of G are available. Otherwise, each item is
an available edge (with an optional weight).
In the unweighted case, each item is an edge (u, v).
In the weighted case, each item is a 3-tuple (u, v, d) or a dict with items (u, v):
d. The third item, d, can be a dictionary or a real number. If d is a dictionary d[weight]
correspondings to the weight.
• weight (string) – key to use to find weights if avail is a set of 3-tuples where the third
item in each tuple is a dictionary.
• partial (boolean) – If partial is True and no feasible k-edge-augmentation exists, then all a
partial k-edge-augmentation is generated. Adding the edges in a partial augmentation to G,
minimizes the number of k-edge-connected components and maximizes the edge connectiv-
ity between those components. For details, see partial_k_edge_augmentation().
Yields edge (tuple) – Edges that, once added to G, would cause G to become k-edge-connected.
If partial is False, an error is raised if this is not possible. Otherwise, generated edges form a
partial augmentation, which k-edge-connects any part of G where it is possible, and maximally
connects the remaining parts.
Raises
• NetworkXUnfeasible – If partial is False and no k-edge-augmentation exists.
• NetworkXNotImplemented – If the input graph is directed or a multigraph.
• ValueError: – If k is less than 1

Notes

When k=1 this returns an optimal solution.


When k=2 and avail is None, this returns an optimal solution. Otherwise when k=2, this returns a 2-
approximation of the optimal solution.
For k>3, this problem is NP-hard and this uses a randomized algorithm that produces a feasible solution,
but provides no guarantees on the solution weight.

Example

>>> # Unweighted cases


>>> G = nx.path_graph((1, 2, 3, 4))
>>> G.add_node(5)
>>> sorted(nx.k_edge_augmentation(G, k=1))
[(1, 5)]
>>> sorted(nx.k_edge_augmentation(G, k=2))
[(1, 5), (5, 4)]
>>> sorted(nx.k_edge_augmentation(G, k=3))
[(1, 4), (1, 5), (2, 5), (3, 5), (4, 5)]
>>> complement = list(nx.k_edge_augmentation(G, k=5, partial=True))
>>> G.add_edges_from(complement)
(continues on next page)

290 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

(continued from previous page)


>>> nx.edge_connectivity(G)
4

Example

>>> # Weighted cases


>>> G = nx.path_graph((1, 2, 3, 4))
>>> G.add_node(5)
>>> # avail can be a tuple with a dict
>>> avail = [(1, 5, {"weight": 11}), (2, 5, {"weight": 10})]
>>> sorted(nx.k_edge_augmentation(G, k=1, avail=avail, weight="weight"))
[(2, 5)]
>>> # or avail can be a 3-tuple with a real number
>>> avail = [(1, 5, 11), (2, 5, 10), (4, 3, 1), (4, 5, 51)]
>>> sorted(nx.k_edge_augmentation(G, k=2, avail=avail))
[(1, 5), (2, 5), (4, 5)]
>>> # or avail can be a dict
>>> avail = {(1, 5): 11, (2, 5): 10, (4, 3): 1, (4, 5): 51}
>>> sorted(nx.k_edge_augmentation(G, k=2, avail=avail))
[(1, 5), (2, 5), (4, 5)]
>>> # If augmentation is infeasible, then a partial solution can be found
>>> avail = {(1, 5): 11}
>>> sorted(nx.k_edge_augmentation(G, k=2, avail=avail, partial=True))
[(1, 5)]

[Link].edge_augmentation.is_k_edge_connected

is_k_edge_connected(G, k)
Tests to see if a graph is k-edge-connected.
Is it impossible to disconnect the graph by removing fewer than k edges? If so, then G is k-edge-connected.
Parameters
• G (NetworkX graph) – An undirected graph.
• k (integer) – edge connectivity to test for
Returns True if G is k-edge-connected.
Return type boolean
See also:
is_locally_k_edge_connected()

3.16. Connectivity 291


NetworkX Reference, Release 2.5

Example

>>> G = nx.barbell_graph(10, 0)
>>> nx.is_k_edge_connected(G, k=1)
True
>>> nx.is_k_edge_connected(G, k=2)
False

[Link].edge_augmentation.is_locally_k_edge_connected

is_locally_k_edge_connected(G, s, t, k)
Tests to see if an edge in a graph is locally k-edge-connected.
Is it impossible to disconnect s and t by removing fewer than k edges? If so, then s and t are locally k-edge-
connected in G.
Parameters
• G (NetworkX graph) – An undirected graph.
• s (node) – Source node
• t (node) – Target node
• k (integer) – local edge connectivity for nodes s and t
Returns True if s and t are locally k-edge-connected in G.
Return type boolean
See also:
is_k_edge_connected()

Example

>>> from [Link] import is_locally_k_edge_connected


>>> G = nx.barbell_graph(10, 0)
>>> is_locally_k_edge_connected(G, 5, 15, k=1)
True
>>> is_locally_k_edge_connected(G, 5, 15, k=2)
False
>>> is_locally_k_edge_connected(G, 1, 5, k=2)
True

3.16.2 K-edge-components

Algorithms for finding k-edge-connected components and subgraphs.


A k-edge-connected component (k-edge-cc) is a maximal set of nodes in G, such that all pairs of node have an edge-
connectivity of at least k.
A k-edge-connected subgraph (k-edge-subgraph) is a maximal set of nodes in G, such that the subgraph of G defined
by the nodes has an edge-connectivity at least k.

292 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

k_edge_components(G, k) Generates nodes in each maximal k-edge-connected


component in G.
k_edge_subgraphs(G, k) Generates nodes in each maximal k-edge-connected
subgraph in G.
bridge_components(G) Finds all bridge-connected components G.
EdgeComponentAuxGraph() A simple algorithm to find all k-edge-connected com-
ponents in a graph.

[Link].edge_kcomponents.k_edge_components

k_edge_components(G, k)
Generates nodes in each maximal k-edge-connected component in G.
Parameters
• G (NetworkX graph)
• k (Integer) – Desired edge connectivity
Returns k_edge_components – will have k-edge-connectivity in the graph G.
Return type a generator of k-edge-ccs. Each set of returned nodes
See also:
local_edge_connectivity()
k_edge_subgraphs() similar to this function, but the subgraph defined by the nodes must also have k-
edge-connectivity.
k_components() similar to this function, but uses node-connectivity instead of edge-connectivity

Raises
• NetworkXNotImplemented – If the input graph is a multigraph.
• ValueError: – If k is less than 1

Notes

Attempts to use the most efficient implementation available based on k. If k=1, this is simply simply connected
components for directed graphs and connected components for undirected graphs. If k=2 on an efficient bridge
connected component algorithm from _[1] is run based on the chain decomposition. Otherwise, the algorithm
from _[2] is used.

Example

>>> import itertools as it


>>> from [Link] import pairwise
>>> paths = [
... (1, 2, 4, 3, 1, 4),
... (5, 6, 7, 8, 5, 7, 8, 6),
... ]
>>> G = [Link]()
>>> G.add_nodes_from([Link](*paths))
>>> G.add_edges_from([Link](*[pairwise(path) for path in paths]))
(continues on next page)

3.16. Connectivity 293


NetworkX Reference, Release 2.5

(continued from previous page)


>>> # note this returns {1, 4} unlike k_edge_subgraphs
>>> sorted(map(sorted, nx.k_edge_components(G, k=3)))
[[1, 4], [2], [3], [5, 6, 7, 8]]

References

[Link].edge_kcomponents.k_edge_subgraphs

k_edge_subgraphs(G, k)
Generates nodes in each maximal k-edge-connected subgraph in G.
Parameters
• G (NetworkX graph)
• k (Integer) – Desired edge connectivity
Returns k_edge_subgraphs – Each k-edge-subgraph is a maximal set of nodes that defines a sub-
graph of G that is k-edge-connected.
Return type a generator of k-edge-subgraphs
See also:
edge_connectivity()
k_edge_components() similar to this function, but nodes only need to have k-edge-connctivity within the
graph G and the subgraphs might not be k-edge-connected.

Raises
• NetworkXNotImplemented – If the input graph is a multigraph.
• ValueError: – If k is less than 1

Notes

Attempts to use the most efficient implementation available based on k. If k=1, or k=2 and the graph is undi-
rected, then this simply calls k_edge_components. Otherwise the algorithm from _[1] is used.

Example

>>> import itertools as it


>>> from [Link] import pairwise
>>> paths = [
... (1, 2, 4, 3, 1, 4),
... (5, 6, 7, 8, 5, 7, 8, 6),
... ]
>>> G = [Link]()
>>> G.add_nodes_from([Link](*paths))
>>> G.add_edges_from([Link](*[pairwise(path) for path in paths]))
>>> # note this does not return {1, 4} unlike k_edge_components
>>> sorted(map(sorted, nx.k_edge_subgraphs(G, k=3)))
[[1], [2], [3], [4], [5, 6, 7, 8]]

294 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

References

[Link].edge_kcomponents.bridge_components

bridge_components(G)
Finds all bridge-connected components G.
Parameters G (NetworkX undirected graph)
Returns bridge_components
Return type a generator of 2-edge-connected components
See also:

k_edge_subgraphs() this function is a special case for an undirected graph where k=2.
biconnected_components() similar to this function, but is defined using 2-node-connectivity instead of
2-edge-connectivity.

Raises NetworkXNotImplemented – If the input graph is directed or a multigraph.

Notes

Bridge-connected components are also known as 2-edge-connected components.

Example

>>> # The barbell graph with parameter zero has a single bridge
>>> G = nx.barbell_graph(5, 0)
>>> from [Link].edge_kcomponents import bridge_
˓→components

>>> sorted(map(sorted, bridge_components(G)))


[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]

[Link].edge_kcomponents.EdgeComponentAuxGraph

class EdgeComponentAuxGraph
A simple algorithm to find all k-edge-connected components in a graph.
Constructing the AuxillaryGraph (which may take some time) allows for the k-edge-ccs to be found in linear
time for arbitrary k.

Notes

This implementation is based on1 . The idea is to construct an auxiliary graph from which the k-edge-ccs can be
extracted in linear time. The auxiliary graph is constructed in 𝑂(|𝑉 | · 𝐹 ) operations, where F is the complexity
of max flow. Querying the components takes an additional 𝑂(|𝑉 |) operations. This algorithm can be slow for
large graphs, but it handles an arbitrary k and works for both directed and undirected inputs.
The undirected case for k=1 is exactly connected components. The undirected case for k=2 is exactly bridge
connected components. The directed case for k=1 is exactly strongly connected components.
1 Wang, Tianhao, et al. (2015) A simple algorithm for finding all k-edge-connected components. [Link]

1371/[Link].0136264

3.16. Connectivity 295


NetworkX Reference, Release 2.5

References

Example

>>> import itertools as it


>>> from [Link] import pairwise
>>> from [Link] import EdgeComponentAuxGraph
>>> # Build an interesting graph with multiple levels of k-edge-ccs
>>> paths = [
... (1, 2, 3, 4, 1, 3, 4, 2), # a 3-edge-cc (a 4 clique)
... (5, 6, 7, 5), # a 2-edge-cc (a 3 clique)
... (1, 5), # combine first two ccs into a 1-edge-cc
... (0,), # add an additional disconnected 1-edge-cc
... ]
>>> G = [Link]()
>>> G.add_nodes_from([Link](*paths))
>>> G.add_edges_from([Link](*[pairwise(path) for path in paths]))
>>> # Constructing the AuxGraph takes about O(n ** 4)
>>> aux_graph = [Link](G)
>>> # Once constructed, querying takes O(n)
>>> sorted(map(sorted, aux_graph.k_edge_components(k=1)))
[[0], [1, 2, 3, 4, 5, 6, 7]]
>>> sorted(map(sorted, aux_graph.k_edge_components(k=2)))
[[0], [1, 2, 3, 4], [5, 6, 7]]
>>> sorted(map(sorted, aux_graph.k_edge_components(k=3)))
[[0], [1, 2, 3, 4], [5], [6], [7]]
>>> sorted(map(sorted, aux_graph.k_edge_components(k=4)))
[[0], [1], [2], [3], [4], [5], [6], [7]]

Example

>>> # The auxiliary graph is primarilly used for k-edge-ccs but it


>>> # can also speed up the queries of k-edge-subgraphs by refining the
>>> # search space.
>>> import itertools as it
>>> from [Link] import pairwise
>>> from [Link] import EdgeComponentAuxGraph
>>> paths = [
... (1, 2, 4, 3, 1, 4),
... ]
>>> G = [Link]()
>>> G.add_nodes_from([Link](*paths))
>>> G.add_edges_from([Link](*[pairwise(path) for path in paths]))
>>> aux_graph = [Link](G)
>>> sorted(map(sorted, aux_graph.k_edge_subgraphs(k=3)))
[[1], [2], [3], [4]]
>>> sorted(map(sorted, aux_graph.k_edge_components(k=3)))
[[1, 4], [2], [3]]

__init__()
Initialize self. See help(type(self)) for accurate signature.

296 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Methods

__init__() Initialize self.


construct(G) Builds an auxiliary graph encoding edge-
connectivity between nodes.
k_edge_components(k) Queries the auxiliary graph for k-edge-connected
components.
k_edge_subgraphs(k) Queries the auxiliary graph for k-edge-connected
subgraphs.

3.16.3 K-node-components

Moody and White algorithm for k-components

k_components(G[, flow_func]) Returns the k-component structure of a graph G.

[Link].k_components

k_components(G, flow_func=None)
Returns the k-component structure of a graph G.
A k-component is a maximal subgraph of a graph G that has, at least, node connectivity k: we need to remove at
least k nodes to break it into more components. k-components have an inherent hierarchical structure because
they are nested in terms of connectivity: a connected graph can contain several 2-components, each of which
can contain one or more 3-components, and so forth.
Parameters
• G (NetworkX graph)
• flow_func (function) – Function to perform the underlying flow computations. Default value
edmonds_karp(). This function performs better in sparse graphs with right tailed degree
distributions. shortest_augmenting_path() will perform better in denser graphs.
Returns k_components – Dictionary with all connectivity levels k in the input Graph as keys and a
list of sets of nodes that form a k-component of level k as values.
Return type dict
Raises NetworkXNotImplemented – If the input graph is directed.

Examples

>>> # Petersen graph has 10 nodes and it is triconnected, thus all


>>> # nodes are in a single component on all three connectivity levels
>>> G = nx.petersen_graph()
>>> k_components = nx.k_components(G)

3.16. Connectivity 297


NetworkX Reference, Release 2.5

Notes

Moody and White1 (appendix A) provide an algorithm for identifying k-components in a graph, which is
based on Kanevsky’s algorithm2 for finding all minimum-size node cut-sets of a graph (implemented in
all_node_cuts() function):
1. Compute node connectivity, k, of the input graph G.
2. Identify all k-cutsets at the current level of connectivity using Kanevsky’s algorithm.
3. Generate new graph components based on the removal of these cutsets. Nodes in a cutset belong to both
sides of the induced cut.
4. If the graph is neither complete nor trivial, return to 1; else end.
This implementation also uses some heuristics (see3 for details) to speed up the computation.
See also:
node_connectivity(), all_node_cuts()
biconnected_components() special case of this function when k=2
k_edge_components() similar to this function, but uses edge-connectivity instead of node-connectivity

References

3.16.4 K-node-cutsets

Kanevsky all minimum node k cutsets algorithm.

all_node_cuts(G[, k, flow_func]) Returns all minimum k cutsets of an undirected graph


G.

[Link].all_node_cuts

all_node_cuts(G, k=None, flow_func=None)


Returns all minimum k cutsets of an undirected graph G.
This implementation is based on Kanevsky’s algorithm1 for finding all minimum-size node cut-sets of an undi-
rected graph G; ie the set (or sets) of nodes of cardinality equal to the node connectivity of G. Thus if removed,
would break G into two or more connected components.
Parameters
• G (NetworkX graph) – Undirected graph
• k (Integer) – Node connectivity of the input graph. If k is None, then it is computed. Default
value: None.
• flow_func (function) – Function to perform the underlying flow computations. Default value
1 Moody, J. and D. White (2003). Social cohesion and embeddedness: A hierarchical conception of social groups. American Sociological

Review 68(1), 103–28. [Link]


2 Kanevsky, A. (1993). Finding all minimum-size separating vertex sets in a graph. Networks 23(6), 533–541. [Link]

doi/10.1002/net.3230230604/abstract
3 Torrents, J. and F. Ferraro (2015). Structural Cohesion: Visualization and Heuristics for Fast Computation. [Link]
1 Kanevsky, A. (1993). Finding all minimum-size separating vertex sets in a graph. Networks 23(6), 533–541. [Link]

doi/10.1002/net.3230230604/abstract

298 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

edmonds_karp. This function performs better in sparse graphs with right tailed degree dis-
tributions. shortest_augmenting_path will perform better in denser graphs.
Returns cuts – Each node cutset has cardinality equal to the node connectivity of the input graph.
Return type a generator of node cutsets

Examples

>>> # A two-dimensional grid graph has 4 cutsets of cardinality 2


>>> G = nx.grid_2d_graph(5, 5)
>>> cutsets = list(nx.all_node_cuts(G))
>>> len(cutsets)
4
>>> all(2 == len(cutset) for cutset in cutsets)
True
>>> nx.node_connectivity(G)
2

Notes

This implementation is based on the sequential algorithm for finding all minimum-size separating vertex sets in
a graph1 . The main idea is to compute minimum cuts using local maximum flow computations among a set of
nodes of highest degree and all other non-adjacent nodes in the Graph. Once we find a minimum cut, we add an
edge between the high degree node and the target node of the local maximum flow computation to make sure
that we will not find that minimum cut again.
See also:
node_connectivity(), edmonds_karp(), shortest_augmenting_path()

References

3.16.5 Flow-based disjoint paths

Flow based node and edge disjoint paths.

edge_disjoint_paths(G, s, t[, flow_func, . . . ]) Returns the edges disjoint paths between source and tar-
get.
node_disjoint_paths(G, s, t[, flow_func, . . . ]) Computes node disjoint paths between source and tar-
get.

[Link].disjoint_paths.edge_disjoint_paths

edge_disjoint_paths(G, s, t, flow_func=None, cutoff=None, auxiliary=None, residual=None)


Returns the edges disjoint paths between source and target.
Edge disjoint paths are paths that do not share any edge. The number of edge disjoint paths between source and
target is equal to their edge connectivity.
Parameters
• G (NetworkX graph)

3.16. Connectivity 299


NetworkX Reference, Release 2.5

• s (node) – Source node for the flow.


• t (node) – Sink node for the flow.
• flow_func (function) – A function for computing the maximum flow among a pair of
nodes. The function has to accept at least three parameters: a Digraph, a source node,
and a target node. And return a residual network that follows NetworkX conventions (see
maximum_flow() for details). If flow_func is None, the default maximum flow function
(edmonds_karp()) is used. The choice of the default function may change from version
to version and should not be relied on. Default value: None.
• cutoff (int) – Maximum number of paths to yield. Some of the maximum flow algorithms,
such as edmonds_karp() (the default) and shortest_augmenting_path() sup-
port the cutoff parameter, and will terminate when the flow value reaches or exceeds the
cutoff. Other algorithms will ignore this parameter. Default value: None.
• auxiliary (NetworkX DiGraph) – Auxiliary digraph to compute flow based edge connectiv-
ity. It has to have a graph attribute called mapping with a dictionary mapping node names
in G and in the auxiliary digraph. If provided it will be reused instead of recreated. Default
value: None.
• residual (NetworkX DiGraph) – Residual network to compute maximum flow. If provided
it will be reused instead of recreated. Default value: None.
Returns paths – A generator of edge independent paths.
Return type generator
Raises
• NetworkXNoPath – If there is no path between source and target.
• NetworkXError – If source or target are not in the graph G.
See also:
node_disjoint_paths(), edge_connectivity(), maximum_flow(), edmonds_karp(),
preflow_push(), shortest_augmenting_path()

Examples

We use in this example the platonic icosahedral graph, which has node edge connectivity 5, thus there are 5 edge
disjoint paths between any pair of nodes.

>>> G = nx.icosahedral_graph()
>>> len(list(nx.edge_disjoint_paths(G, 0, 6)))
5

If you need to compute edge disjoint paths on several pairs of nodes in the same graph, it is recommended that
you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for edge connectivity,
and the residual network for the underlying maximum flow computation.
Example of how to compute edge disjoint paths among all pairs of nodes of the platonic icosahedral graph
reusing the data structures.

>>> import itertools


>>> # You also have to explicitly import the function for
>>> # building the auxiliary digraph from the connectivity package
>>> from [Link] import build_auxiliary_edge_connectivity
>>> H = build_auxiliary_edge_connectivity(G)
(continues on next page)

300 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

(continued from previous page)


>>> # And the function for building the residual network from the
>>> # flow package
>>> from [Link] import build_residual_network
>>> # Note that the auxiliary digraph has an edge attribute named capacity
>>> R = build_residual_network(H, "capacity")
>>> result = {n: {} for n in G}
>>> # Reuse the auxiliary digraph and the residual network by passing them
>>> # as arguments
>>> for u, v in [Link](G, 2):
... k = len(list(nx.edge_disjoint_paths(G, u, v, auxiliary=H, residual=R)))
... result[u][v] = k
>>> all(result[u][v] == 5 for u, v in [Link](G, 2))
True

You can also use alternative flow algorithms for computing edge disjoint paths. For instance, in dense
networks the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp() which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.

>>> from [Link] import shortest_augmenting_path


>>> len(list(nx.edge_disjoint_paths(G, 0, 6, flow_func=shortest_augmenting_path)))
5

Notes

This is a flow based implementation of edge disjoint paths. We compute the maximum flow between source and
target on an auxiliary directed network. The saturated edges in the residual network after running the maximum
flow algorithm correspond to edge disjoint paths between source and target in the original network. This function
handles both directed and undirected graphs, and can use all flow algorithms from NetworkX flow package.

[Link].disjoint_paths.node_disjoint_paths

node_disjoint_paths(G, s, t, flow_func=None, cutoff=None, auxiliary=None, residual=None)


Computes node disjoint paths between source and target.
Node disjoint paths are paths that only share their first and last nodes. The number of node independent paths
between two nodes is equal to their local node connectivity.
Parameters
• G (NetworkX graph)
• s (node) – Source node.
• t (node) – Target node.
• flow_func (function) – A function for computing the maximum flow among a pair of
nodes. The function has to accept at least three parameters: a Digraph, a source node,
and a target node. And return a residual network that follows NetworkX conventions (see
maximum_flow() for details). If flow_func is None, the default maximum flow function
(edmonds_karp()) is used. See below for details. The choice of the default function
may change from version to version and should not be relied on. Default value: None.
• cutoff (int) – Maximum number of paths to yield. Some of the maximum flow algorithms,
such as edmonds_karp() (the default) and shortest_augmenting_path() sup-

3.16. Connectivity 301


NetworkX Reference, Release 2.5

port the cutoff parameter, and will terminate when the flow value reaches or exceeds the
cutoff. Other algorithms will ignore this parameter. Default value: None.
• auxiliary (NetworkX DiGraph) – Auxiliary digraph to compute flow based node connectiv-
ity. It has to have a graph attribute called mapping with a dictionary mapping node names
in G and in the auxiliary digraph. If provided it will be reused instead of recreated. Default
value: None.
• residual (NetworkX DiGraph) – Residual network to compute maximum flow. If provided
it will be reused instead of recreated. Default value: None.
Returns paths – Generator of node disjoint paths.
Return type generator
Raises
• NetworkXNoPath – If there is no path between source and target.
• NetworkXError – If source or target are not in the graph G.

Examples

We use in this example the platonic icosahedral graph, which has node node connectivity 5, thus there are 5
node disjoint paths between any pair of non neighbor nodes.

>>> G = nx.icosahedral_graph()
>>> len(list(nx.node_disjoint_paths(G, 0, 6)))
5

If you need to compute node disjoint paths between several pairs of nodes in the same graph, it is recommended
that you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for node con-
nectivity and node cuts, and the residual network for the underlying maximum flow computation.
Example of how to compute node disjoint paths reusing the data structures:

>>> # You also have to explicitly import the function for


>>> # building the auxiliary digraph from the connectivity package
>>> from [Link] import build_auxiliary_node_connectivity
>>> H = build_auxiliary_node_connectivity(G)
>>> # And the function for building the residual network from the
>>> # flow package
>>> from [Link] import build_residual_network
>>> # Note that the auxiliary digraph has an edge attribute named capacity
>>> R = build_residual_network(H, "capacity")
>>> # Reuse the auxiliary digraph and the residual network by passing them
>>> # as arguments
>>> len(list(nx.node_disjoint_paths(G, 0, 6, auxiliary=H, residual=R)))
5

You can also use alternative flow algorithms for computing node disjoint paths. For instance, in dense
networks the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp() which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.

>>> from [Link] import shortest_augmenting_path


>>> len(list(nx.node_disjoint_paths(G, 0, 6, flow_func=shortest_augmenting_path)))
5

302 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Notes

This is a flow based implementation of node disjoint paths. We compute the maximum flow between source
and target on an auxiliary directed network. The saturated edges in the residual network after running the
maximum flow algorithm correspond to node disjoint paths between source and target in the original network.
This function handles both directed and undirected graphs, and can use all flow algorithms from NetworkX flow
package.
See also:
edge_disjoint_paths(), node_connectivity(), maximum_flow(), edmonds_karp(),
preflow_push(), shortest_augmenting_path()

3.16.6 Flow-based Connectivity

Flow based connectivity algorithms

average_node_connectivity(G[, flow_func]) Returns the average connectivity of a graph G.


all_pairs_node_connectivity(G[, nbunch, Compute node connectivity between all pairs of nodes
. . . ]) of G.
edge_connectivity(G[, s, t, flow_func, cutoff]) Returns the edge connectivity of the graph or digraph G.
local_edge_connectivity(G, s, t[, . . . ]) Returns local edge connectivity for nodes s and t in G.
local_node_connectivity(G, s, t[, . . . ]) Computes local node connectivity for nodes s and t.
node_connectivity(G[, s, t, flow_func]) Returns node connectivity for a graph or digraph G.

[Link].average_node_connectivity

average_node_connectivity(G, flow_func=None)
Returns the average connectivity of a graph G.
The average connectivity bar{kappa} of a graph G is the average of local node connectivity over all pairs of
nodes of G1 .
∑︀
𝑢,𝑣 𝜅𝐺 (𝑢, 𝑣)
𝜅
¯ (𝐺) = (︀𝑛)︀
2

Parameters
• G (NetworkX graph) – Undirected graph
• flow_func (function) – A function for computing the maximum flow among a pair of
nodes. The function has to accept at least three parameters: a Digraph, a source node,
and a target node. And return a residual network that follows NetworkX conventions (see
maximum_flow() for details). If flow_func is None, the default maximum flow function
(edmonds_karp()) is used. See local_node_connectivity() for details. The
choice of the default function may change from version to version and should not be relied
on. Default value: None.
Returns K – Average node connectivity
Return type float
See also:
1 Beineke, L., O. Oellermann, and R. Pippert (2002). The average connectivity of a graph. Discrete mathematics 252(1-3), 31-45. http:

//[Link]/science/article/pii/S0012365X01001807

3.16. Connectivity 303


NetworkX Reference, Release 2.5

local_node_connectivity(), node_connectivity(), edge_connectivity(),


maximum_flow(), edmonds_karp(), preflow_push(), shortest_augmenting_path()

References

[Link].all_pairs_node_connectivity

all_pairs_node_connectivity(G, nbunch=None, flow_func=None)


Compute node connectivity between all pairs of nodes of G.
Parameters
• G (NetworkX graph) – Undirected graph
• nbunch (container) – Container of nodes. If provided node connectivity will be computed
only over pairs of nodes in nbunch.
• flow_func (function) – A function for computing the maximum flow among a pair of
nodes. The function has to accept at least three parameters: a Digraph, a source node,
and a target node. And return a residual network that follows NetworkX conventions (see
maximum_flow() for details). If flow_func is None, the default maximum flow function
(edmonds_karp()) is used. See below for details. The choice of the default function
may change from version to version and should not be relied on. Default value: None.
Returns all_pairs – A dictionary with node connectivity between all pairs of nodes in G, or in
nbunch if provided.
Return type dict
See also:
local_node_connectivity(), edge_connectivity(), local_edge_connectivity(),
maximum_flow(), edmonds_karp(), preflow_push(), shortest_augmenting_path()

[Link].edge_connectivity

edge_connectivity(G, s=None, t=None, flow_func=None, cutoff=None)


Returns the edge connectivity of the graph or digraph G.
The edge connectivity is equal to the minimum number of edges that must be removed to disconnect G or render
it trivial. If source and target nodes are provided, this function returns the local edge connectivity: the minimum
number of edges that must be removed to break all paths from source to target in G.
Parameters
• G (NetworkX graph) – Undirected or directed graph
• s (node) – Source node. Optional. Default value: None.
• t (node) – Target node. Optional. Default value: None.
• flow_func (function) – A function for computing the maximum flow among a pair of
nodes. The function has to accept at least three parameters: a Digraph, a source node,
and a target node. And return a residual network that follows NetworkX conventions (see
maximum_flow() for details). If flow_func is None, the default maximum flow function
(edmonds_karp()) is used. See below for details. The choice of the default function
may change from version to version and should not be relied on. Default value: None.

304 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

• cutoff (integer, float) – If specified, the maximum flow algorithm will terminate when the
flow value reaches or exceeds the cutoff. This is only for the algorithms that support the cut-
off parameter: e.g., edmonds_karp() and shortest_augmenting_path(). Other
algorithms will ignore this parameter. Default value: None.
Returns K – Edge connectivity for G, or local edge connectivity if source and target were provided
Return type integer

Examples

>>> # Platonic icosahedral graph is 5-edge-connected


>>> G = nx.icosahedral_graph()
>>> nx.edge_connectivity(G)
5

You can use alternative flow algorithms for the underlying maximum flow computation. In dense net-
works the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp(), which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.

>>> from [Link] import shortest_augmenting_path


>>> nx.edge_connectivity(G, flow_func=shortest_augmenting_path)
5

If you specify a pair of nodes (source and target) as parameters, this function returns the value of local edge
connectivity.

>>> nx.edge_connectivity(G, 3, 7)
5

If you need to perform several local computations among different pairs of nodes on the same graph,
it is recommended that you reuse the data structures used in the maximum flow computations. See
local_edge_connectivity() for details.

Notes

This is a flow based implementation of global edge connectivity. For undirected graphs the algorithm works by
finding a ‘small’ dominating set of nodes of G (see algorithm 7 in1 ) and computing local maximum flow (see
local_edge_connectivity()) between an arbitrary node in the dominating set and the rest of nodes in
it. This is an implementation of algorithm 6 in1 . For directed graphs, the algorithm does n calls to the maximum
flow function. This is an implementation of algorithm 8 in1 .
See also:
local_edge_connectivity(), local_node_connectivity(), node_connectivity(),
maximum_flow(), edmonds_karp(), preflow_push(), shortest_augmenting_path(),
k_edge_components(), k_edge_subgraphs()
1 Abdol-Hossein Esfahanian. Connectivity Algorithms. [Link]

3.16. Connectivity 305


NetworkX Reference, Release 2.5

References

[Link].local_edge_connectivity

local_edge_connectivity(G, s, t, flow_func=None, auxiliary=None, residual=None, cutoff=None)


Returns local edge connectivity for nodes s and t in G.
Local edge connectivity for two nodes s and t is the minimum number of edges that must be removed to discon-
nect them.
This is a flow based implementation of edge connectivity. We compute the maximum flow on an auxiliary
digraph build from the original network (see below for details). This is equal to the local edge connectivity
because the value of a maximum s-t-flow is equal to the capacity of a minimum s-t-cut (Ford and Fulkerson
theorem)1 .
Parameters
• G (NetworkX graph) – Undirected or directed graph
• s (node) – Source node
• t (node) – Target node
• flow_func (function) – A function for computing the maximum flow among a pair of
nodes. The function has to accept at least three parameters: a Digraph, a source node,
and a target node. And return a residual network that follows NetworkX conventions (see
maximum_flow() for details). If flow_func is None, the default maximum flow function
(edmonds_karp()) is used. See below for details. The choice of the default function
may change from version to version and should not be relied on. Default value: None.
• auxiliary (NetworkX DiGraph) – Auxiliary digraph for computing flow based edge connec-
tivity. If provided it will be reused instead of recreated. Default value: None.
• residual (NetworkX DiGraph) – Residual network to compute maximum flow. If provided
it will be reused instead of recreated. Default value: None.
• cutoff (integer, float) – If specified, the maximum flow algorithm will terminate when the
flow value reaches or exceeds the cutoff. This is only for the algorithms that support the
cutoff parameter: edmonds_karp() and shortest_augmenting_path(). Other
algorithms will ignore this parameter. Default value: None.
Returns K – local edge connectivity for nodes s and t.
Return type integer

Examples

This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the
connectivity package:

>>> from [Link] import local_edge_connectivity

We use in this example the platonic icosahedral graph, which has edge connectivity 5.

>>> G = nx.icosahedral_graph()
>>> local_edge_connectivity(G, 0, 6)
5

1 Abdol-Hossein Esfahanian. Connectivity Algorithms. [Link]

306 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

If you need to compute local connectivity on several pairs of nodes in the same graph, it is recommended that
you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for edge connectivity,
and the residual network for the underlying maximum flow computation.
Example of how to compute local edge connectivity among all pairs of nodes of the platonic icosahedral graph
reusing the data structures.

>>> import itertools


>>> # You also have to explicitly import the function for
>>> # building the auxiliary digraph from the connectivity package
>>> from [Link] import build_auxiliary_edge_connectivity
>>> H = build_auxiliary_edge_connectivity(G)
>>> # And the function for building the residual network from the
>>> # flow package
>>> from [Link] import build_residual_network
>>> # Note that the auxiliary digraph has an edge attribute named capacity
>>> R = build_residual_network(H, "capacity")
>>> result = [Link](G, dict())
>>> # Reuse the auxiliary digraph and the residual network by passing them
>>> # as parameters
>>> for u, v in [Link](G, 2):
... k = local_edge_connectivity(G, u, v, auxiliary=H, residual=R)
... result[u][v] = k
>>> all(result[u][v] == 5 for u, v in [Link](G, 2))
True

You can also use alternative flow algorithms for computing edge connectivity. For instance, in dense
networks the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp() which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.

>>> from [Link] import shortest_augmenting_path


>>> local_edge_connectivity(G, 0, 6, flow_func=shortest_augmenting_path)
5

Notes

This is a flow based implementation of edge connectivity. We compute the maximum flow using, by default, the
edmonds_karp() algorithm on an auxiliary digraph build from the original input graph:
If the input graph is undirected, we replace each edge (u,`v`) with two reciprocal arcs (u, v) and (v, u) and
then we set the attribute ‘capacity’ for each arc to 1. If the input graph is directed we simply add the ‘capacity’
attribute. This is an implementation of algorithm 1 in1 .
The maximum flow in the auxiliary network is equal to the local edge connectivity because the value of a
maximum s-t-flow is equal to the capacity of a minimum s-t-cut (Ford and Fulkerson theorem).
See also:
edge_connectivity(), local_node_connectivity(), node_connectivity(),
maximum_flow(), edmonds_karp(), preflow_push(), shortest_augmenting_path()

3.16. Connectivity 307


NetworkX Reference, Release 2.5

References

[Link].local_node_connectivity

local_node_connectivity(G, s, t, flow_func=None, auxiliary=None, residual=None, cutoff=None)


Computes local node connectivity for nodes s and t.
Local node connectivity for two non adjacent nodes s and t is the minimum number of nodes that must be
removed (along with their incident edges) to disconnect them.
This is a flow based implementation of node connectivity. We compute the maximum flow on an auxiliary
digraph build from the original input graph (see below for details).
Parameters
• G (NetworkX graph) – Undirected graph
• s (node) – Source node
• t (node) – Target node
• flow_func (function) – A function for computing the maximum flow among a pair of
nodes. The function has to accept at least three parameters: a Digraph, a source node,
and a target node. And return a residual network that follows NetworkX conventions (see
maximum_flow() for details). If flow_func is None, the default maximum flow function
(edmonds_karp()) is used. See below for details. The choice of the default function
may change from version to version and should not be relied on. Default value: None.
• auxiliary (NetworkX DiGraph) – Auxiliary digraph to compute flow based node connectiv-
ity. It has to have a graph attribute called mapping with a dictionary mapping node names
in G and in the auxiliary digraph. If provided it will be reused instead of recreated. Default
value: None.
• residual (NetworkX DiGraph) – Residual network to compute maximum flow. If provided
it will be reused instead of recreated. Default value: None.
• cutoff (integer, float) – If specified, the maximum flow algorithm will terminate when the
flow value reaches or exceeds the cutoff. This is only for the algorithms that support the
cutoff parameter: edmonds_karp() and shortest_augmenting_path(). Other
algorithms will ignore this parameter. Default value: None.
Returns K – local node connectivity for nodes s and t
Return type integer

Examples

This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the
connectivity package:

>>> from [Link] import local_node_connectivity

We use in this example the platonic icosahedral graph, which has node connectivity 5.

>>> G = nx.icosahedral_graph()
>>> local_node_connectivity(G, 0, 6)
5

308 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

If you need to compute local connectivity on several pairs of nodes in the same graph, it is recommended that
you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for node connectivity,
and the residual network for the underlying maximum flow computation.
Example of how to compute local node connectivity among all pairs of nodes of the platonic icosahedral graph
reusing the data structures.

>>> import itertools


>>> # You also have to explicitly import the function for
>>> # building the auxiliary digraph from the connectivity package
>>> from [Link] import build_auxiliary_node_connectivity
...
>>> H = build_auxiliary_node_connectivity(G)
>>> # And the function for building the residual network from the
>>> # flow package
>>> from [Link] import build_residual_network
>>> # Note that the auxiliary digraph has an edge attribute named capacity
>>> R = build_residual_network(H, "capacity")
>>> result = [Link](G, dict())
>>> # Reuse the auxiliary digraph and the residual network by passing them
>>> # as parameters
>>> for u, v in [Link](G, 2):
... k = local_node_connectivity(G, u, v, auxiliary=H, residual=R)
... result[u][v] = k
...
>>> all(result[u][v] == 5 for u, v in [Link](G, 2))
True

You can also use alternative flow algorithms for computing node connectivity. For instance, in dense
networks the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp() which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.

>>> from [Link] import shortest_augmenting_path


>>> local_node_connectivity(G, 0, 6, flow_func=shortest_augmenting_path)
5

Notes

This is a flow based implementation of node connectivity. We compute the maximum flow using, by default,
the edmonds_karp() algorithm (see: maximum_flow()) on an auxiliary digraph build from the original
input graph:
For an undirected graph G having n nodes and m edges we derive a directed graph H with 2n nodes and 2m+n
arcs by replacing each original node v with two nodes v_A, v_B linked by an (internal) arc in H. Then for each
edge (u, v) in G we add two arcs (u_B, v_A) and (v_B, u_A) in H. Finally we set the attribute capacity = 1 for
each arc in H1 .
For a directed graph G having n nodes and m arcs we derive a directed graph H with 2n nodes and m+n arcs by
replacing each original node v with two nodes v_A, v_B linked by an (internal) arc (v_A, v_B) in H. Then for
each arc (u, v) in G we add one arc (u_B, v_A) in H. Finally we set the attribute capacity = 1 for each arc in H.
This is equal to the local node connectivity because the value of a maximum s-t-flow is equal to the capacity of
a minimum s-t-cut.
1 Kammer, Frank and Hanjo Taubig. Graph Connectivity. in Brandes and Erlebach, ‘Network Analysis: Methodological Foundations’,
Lecture Notes in Computer Science, Volume 3418, Springer-Verlag, 2005. [Link]
[Link]

3.16. Connectivity 309


NetworkX Reference, Release 2.5

See also:
local_edge_connectivity(), node_connectivity(), minimum_node_cut(),
maximum_flow(), edmonds_karp(), preflow_push(), shortest_augmenting_path()

References

[Link].node_connectivity

node_connectivity(G, s=None, t=None, flow_func=None)


Returns node connectivity for a graph or digraph G.
Node connectivity is equal to the minimum number of nodes that must be removed to disconnect G or render it
trivial. If source and target nodes are provided, this function returns the local node connectivity: the minimum
number of nodes that must be removed to break all paths from source to target in G.
Parameters
• G (NetworkX graph) – Undirected graph
• s (node) – Source node. Optional. Default value: None.
• t (node) – Target node. Optional. Default value: None.
• flow_func (function) – A function for computing the maximum flow among a pair of
nodes. The function has to accept at least three parameters: a Digraph, a source node,
and a target node. And return a residual network that follows NetworkX conventions (see
maximum_flow() for details). If flow_func is None, the default maximum flow function
(edmonds_karp()) is used. See below for details. The choice of the default function
may change from version to version and should not be relied on. Default value: None.
Returns K – Node connectivity of G, or local node connectivity if source and target are provided.
Return type integer

Examples

>>> # Platonic icosahedral graph is 5-node-connected


>>> G = nx.icosahedral_graph()
>>> nx.node_connectivity(G)
5

You can use alternative flow algorithms for the underlying maximum flow computation. In dense net-
works the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp(), which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.

>>> from [Link] import shortest_augmenting_path


>>> nx.node_connectivity(G, flow_func=shortest_augmenting_path)
5

If you specify a pair of nodes (source and target) as parameters, this function returns the value of local node
connectivity.

>>> nx.node_connectivity(G, 3, 7)
5

310 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

If you need to perform several local computations among different pairs of nodes on the same graph,
it is recommended that you reuse the data structures used in the maximum flow computations. See
local_node_connectivity() for details.

Notes

This is a flow based implementation of node connectivity. The algorithm works by solving 𝑂((𝑛 − 𝛿 − 1 + 𝛿(𝛿 −
1)/2)) maximum flow problems on an auxiliary digraph. Where 𝛿 is the minimum degree of G. For details about
the auxiliary digraph and the computation of local node connectivity see local_node_connectivity().
This implementation is based on algorithm 11 in1 .
See also:
local_node_connectivity(), edge_connectivity(), maximum_flow(),
edmonds_karp(), preflow_push(), shortest_augmenting_path()

References

3.16.7 Flow-based Minimum Cuts

Flow based cut algorithms

minimum_edge_cut(G[, s, t, flow_func]) Returns a set of edges of minimum cardinality that dis-


connects G.
minimum_node_cut(G[, s, t, flow_func]) Returns a set of nodes of minimum cardinality that dis-
connects G.
minimum_st_edge_cut(G, s, t[, flow_func, . . . ]) Returns the edges of the cut-set of a minimum (s, t)-cut.
minimum_st_node_cut(G, s, t[, flow_func, . . . ]) Returns a set of nodes of minimum cardinality that dis-
connect source from target in G.

[Link].minimum_edge_cut

minimum_edge_cut(G, s=None, t=None, flow_func=None)


Returns a set of edges of minimum cardinality that disconnects G.
If source and target nodes are provided, this function returns the set of edges of minimum cardinality that, if
removed, would break all paths among source and target in G. If not, it returns a set of edges of minimum
cardinality that disconnects G.
Parameters
• G (NetworkX graph)
• s (node) – Source node. Optional. Default value: None.
• t (node) – Target node. Optional. Default value: None.
• flow_func (function) – A function for computing the maximum flow among a pair of
nodes. The function has to accept at least three parameters: a Digraph, a source node,
and a target node. And return a residual network that follows NetworkX conventions (see
maximum_flow() for details). If flow_func is None, the default maximum flow function
(edmonds_karp()) is used. See below for details. The choice of the default function
may change from version to version and should not be relied on. Default value: None.
1 Abdol-Hossein Esfahanian. Connectivity Algorithms. [Link]

3.16. Connectivity 311


NetworkX Reference, Release 2.5

Returns cutset – Set of edges that, if removed, would disconnect G. If source and target nodes are
provided, the set contains the edges that if removed, would destroy all paths between source and
target.
Return type set

Examples

>>> # Platonic icosahedral graph has edge connectivity 5


>>> G = nx.icosahedral_graph()
>>> len(nx.minimum_edge_cut(G))
5

You can use alternative flow algorithms for the underlying maximum flow computation. In dense net-
works the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp(), which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.

>>> from [Link] import shortest_augmenting_path


>>> len(nx.minimum_edge_cut(G, flow_func=shortest_augmenting_path))
5

If you specify a pair of nodes (source and target) as parameters, this function returns the value of local edge
connectivity.

>>> nx.edge_connectivity(G, 3, 7)
5

If you need to perform several local computations among different pairs of nodes on the same graph,
it is recommended that you reuse the data structures used in the maximum flow computations. See
local_edge_connectivity() for details.

Notes

This is a flow based implementation of minimum edge cut. For undirected graphs the algorithm works by
finding a ‘small’ dominating set of nodes of G (see algorithm 7 in1 ) and computing the maximum flow between
an arbitrary node in the dominating set and the rest of nodes in it. This is an implementation of algorithm 6
in1 . For directed graphs, the algorithm does n calls to the max flow function. The function raises an error if the
directed graph is not weakly connected and returns an empty set if it is weakly connected. It is an implementation
of algorithm 8 in1 .
See also:
minimum_st_edge_cut(), minimum_node_cut(), stoer_wagner(),
node_connectivity(), edge_connectivity(), maximum_flow(), edmonds_karp(),
preflow_push(), shortest_augmenting_path()
1 Abdol-Hossein Esfahanian. Connectivity Algorithms. [Link]

312 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

References

[Link].minimum_node_cut

minimum_node_cut(G, s=None, t=None, flow_func=None)


Returns a set of nodes of minimum cardinality that disconnects G.
If source and target nodes are provided, this function returns the set of nodes of minimum cardinality that, if
removed, would destroy all paths among source and target in G. If not, it returns a set of nodes of minimum
cardinality that disconnects G.
Parameters
• G (NetworkX graph)
• s (node) – Source node. Optional. Default value: None.
• t (node) – Target node. Optional. Default value: None.
• flow_func (function) – A function for computing the maximum flow among a pair of
nodes. The function has to accept at least three parameters: a Digraph, a source node,
and a target node. And return a residual network that follows NetworkX conventions (see
maximum_flow() for details). If flow_func is None, the default maximum flow function
(edmonds_karp()) is used. See below for details. The choice of the default function
may change from version to version and should not be relied on. Default value: None.
Returns cutset – Set of nodes that, if removed, would disconnect G. If source and target nodes are
provided, the set contains the nodes that if removed, would destroy all paths between source and
target.
Return type set

Examples

>>> # Platonic icosahedral graph has node connectivity 5


>>> G = nx.icosahedral_graph()
>>> node_cut = nx.minimum_node_cut(G)
>>> len(node_cut)
5

You can use alternative flow algorithms for the underlying maximum flow computation. In dense net-
works the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp(), which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.

>>> from [Link] import shortest_augmenting_path


>>> node_cut == nx.minimum_node_cut(G, flow_func=shortest_augmenting_path)
True

If you specify a pair of nodes (source and target) as parameters, this function returns a local st node cut.

>>> len(nx.minimum_node_cut(G, 3, 7))


5

If you need to perform several local st cuts among different pairs of nodes on the same graph, it is recommended
that you reuse the data structures used in the maximum flow computations. See minimum_st_node_cut()
for details.

3.16. Connectivity 313


NetworkX Reference, Release 2.5

Notes

This is a flow based implementation of minimum node cut. The algorithm is based in solving a number of
maximum flow computations to determine the capacity of the minimum cut on an auxiliary directed network that
corresponds to the minimum node cut of G. It handles both directed and undirected graphs. This implementation
is based on algorithm 11 in1 .
See also:
minimum_st_node_cut(), minimum_cut(), minimum_edge_cut(), stoer_wagner(),
node_connectivity(), edge_connectivity(), maximum_flow(), edmonds_karp(),
preflow_push(), shortest_augmenting_path()

References

[Link].minimum_st_edge_cut

minimum_st_edge_cut(G, s, t, flow_func=None, auxiliary=None, residual=None)


Returns the edges of the cut-set of a minimum (s, t)-cut.
This function returns the set of edges of minimum cardinality that, if removed, would destroy all paths among
source and target in G. Edge weights are not considered. See minimum_cut() for computing minimum cuts
considering edge weights.
Parameters
• G (NetworkX graph)
• s (node) – Source node for the flow.
• t (node) – Sink node for the flow.
• auxiliary (NetworkX DiGraph) – Auxiliary digraph to compute flow based node connectiv-
ity. It has to have a graph attribute called mapping with a dictionary mapping node names
in G and in the auxiliary digraph. If provided it will be reused instead of recreated. Default
value: None.
• flow_func (function) – A function for computing the maximum flow among a pair of
nodes. The function has to accept at least three parameters: a Digraph, a source node,
and a target node. And return a residual network that follows NetworkX conventions (see
maximum_flow() for details). If flow_func is None, the default maximum flow function
(edmonds_karp()) is used. See node_connectivity() for details. The choice of
the default function may change from version to version and should not be relied on. Default
value: None.
• residual (NetworkX DiGraph) – Residual network to compute maximum flow. If provided
it will be reused instead of recreated. Default value: None.
Returns cutset – Set of edges that, if removed from the graph, will disconnect it.
Return type set
See also:
minimum_cut(), minimum_node_cut(), minimum_edge_cut(), stoer_wagner(),
node_connectivity(), edge_connectivity(), maximum_flow(), edmonds_karp(),
preflow_push(), shortest_augmenting_path()
1 Abdol-Hossein Esfahanian. Connectivity Algorithms. [Link]

314 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

Examples

This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the
connectivity package:

>>> from [Link] import minimum_st_edge_cut

We use in this example the platonic icosahedral graph, which has edge connectivity 5.

>>> G = nx.icosahedral_graph()
>>> len(minimum_st_edge_cut(G, 0, 6))
5

If you need to compute local edge cuts on several pairs of nodes in the same graph, it is recommended that you
reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for edge connectivity,
and the residual network for the underlying maximum flow computation.
Example of how to compute local edge cuts among all pairs of nodes of the platonic icosahedral graph reusing
the data structures.

>>> import itertools


>>> # You also have to explicitly import the function for
>>> # building the auxiliary digraph from the connectivity package
>>> from [Link] import build_auxiliary_edge_connectivity
>>> H = build_auxiliary_edge_connectivity(G)
>>> # And the function for building the residual network from the
>>> # flow package
>>> from [Link] import build_residual_network
>>> # Note that the auxiliary digraph has an edge attribute named capacity
>>> R = build_residual_network(H, "capacity")
>>> result = [Link](G, dict())
>>> # Reuse the auxiliary digraph and the residual network by passing them
>>> # as parameters
>>> for u, v in [Link](G, 2):
... k = len(minimum_st_edge_cut(G, u, v, auxiliary=H, residual=R))
... result[u][v] = k
>>> all(result[u][v] == 5 for u, v in [Link](G, 2))
True

You can also use alternative flow algorithms for computing edge cuts. For instance, in dense networks the algo-
rithm shortest_augmenting_path() will usually perform better than the default edmonds_karp()
which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to
be explicitly imported from the flow package.

>>> from [Link] import shortest_augmenting_path


>>> len(minimum_st_edge_cut(G, 0, 6, flow_func=shortest_augmenting_path))
5

3.16. Connectivity 315


NetworkX Reference, Release 2.5

[Link].minimum_st_node_cut

minimum_st_node_cut(G, s, t, flow_func=None, auxiliary=None, residual=None)


Returns a set of nodes of minimum cardinality that disconnect source from target in G.
This function returns the set of nodes of minimum cardinality that, if removed, would destroy all paths among
source and target in G.
Parameters
• G (NetworkX graph)
• s (node) – Source node.
• t (node) – Target node.
• flow_func (function) – A function for computing the maximum flow among a pair of
nodes. The function has to accept at least three parameters: a Digraph, a source node,
and a target node. And return a residual network that follows NetworkX conventions (see
maximum_flow() for details). If flow_func is None, the default maximum flow function
(edmonds_karp()) is used. See below for details. The choice of the default function
may change from version to version and should not be relied on. Default value: None.
• auxiliary (NetworkX DiGraph) – Auxiliary digraph to compute flow based node connectiv-
ity. It has to have a graph attribute called mapping with a dictionary mapping node names
in G and in the auxiliary digraph. If provided it will be reused instead of recreated. Default
value: None.
• residual (NetworkX DiGraph) – Residual network to compute maximum flow. If provided
it will be reused instead of recreated. Default value: None.
Returns cutset – Set of nodes that, if removed, would destroy all paths between source and target
in G.
Return type set

Examples

This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the
connectivity package:

>>> from [Link] import minimum_st_node_cut

We use in this example the platonic icosahedral graph, which has node connectivity 5.

>>> G = nx.icosahedral_graph()
>>> len(minimum_st_node_cut(G, 0, 6))
5

If you need to compute local st cuts between several pairs of nodes in the same graph, it is recommended that
you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for node connectivity
and node cuts, and the residual network for the underlying maximum flow computation.
Example of how to compute local st node cuts reusing the data structures:

>>> # You also have to explicitly import the function for


>>> # building the auxiliary digraph from the connectivity package
>>> from [Link] import build_auxiliary_node_connectivity
>>> H = build_auxiliary_node_connectivity(G)
(continues on next page)

316 Chapter 3. Algorithms


NetworkX Reference, Release 2.5

(continued from previous page)


>>> # And the function for building the residual network from the
>>> # flow package
>>> from [Link] import build_residual_network
>>> # Note that the auxiliary digraph has an edge attribute named capacity
>>> R = build_residual_network(H, "capacity")
>>> # Reuse the auxiliary digraph and the residual network by passing them
>>> # as parameters
>>> len(minimum_st_node_cut(G, 0, 6, auxiliary=H, residual=R))
5

You can also use alternative flow algorithms for computing minimum st node cuts. For instance, in dense
networks the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp() which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.

>>> from [Link] import shortest_augmenting_path


>>> len(minimum_st_node_cut(G, 0, 6, flow_func=shortest_augmenting_path))
5

Notes

This is a flow based implementation of minimum node cut. The algorithm is based in solving a number of
maximum flow computations to determine the capacity of the minimum cut on an auxiliary directed network that
corresponds to the minimum node cut of G. It handles both directed and undirected graphs. This implementation
is based on algorithm 11 in1 .
See also:
minimum_node_cut(), minimum_edge_cut(), stoer_wagner(), node_connectivity(),
edge_connectivity(), maximum_flow(), edmonds_karp(), preflow_push(),
shortest_augmenting_path()

References

3.16.8 Stoer-Wagner minimum cut

Stoer-Wagner minimum cut algorithm.

stoer_wagner(G[, weight, heap]) Returns the weighted minimum edge cut using the
Stoer-Wagner algorithm.
1 Abdol-Hossein Esfahanian. Connectivity Algorithms. [Link]

3.16. Connectivity 317


NetworkX Reference, Release 2.5

[Link].stoer_wagner

stoer_wagner(G, weight='weight', heap=<class '[Link]'>)


Returns the weighted minimum edge cut using the Stoer-Wagner algorithm.
Determine the minimum edge cut of a connected graph using the Stoer-Wagner algorithm. In weighted cases,
all weights must be nonnegative.
The running time of the algorithm depends on the type of heaps used:

Type of heap Running time


Binary heap 𝑂(𝑛(𝑚 +