ancestors#

ancestors(G, source)[source]#

Returns all nodes having a path to source in G.

Parameters:
GNetworkX Graph
sourcenode in G
Returns:
set()

The ancestors of source in G

Raises:
NetworkXError

If node source is not in G.

See also

descendants

Examples

>>> DG = nx.path_graph(5, create_using=nx.DiGraph)
>>> sorted(nx.ancestors(DG, 2))
[0, 1]

The source node is not an ancestor of itself, but can be included manually:

>>> sorted(nx.ancestors(DG, 2) | {2})
[0, 1, 2]
----

Additional backends implement this function

cugraph : GPU-accelerated backend.

graphblas : OpenMP-enabled sparse linear algebra backend.