dgl.add_edges(g, u, v, data=None, etype=None)[source]

Add the edges to the graph and return a new graph.

The i-th new edge will be from u[i] to v[i]. The IDs of the new edges will start from g.num_edges(etype).

  • u (int, Tensor or iterable[int]) – Source node IDs, u[i] gives the source node for the i-th new edge.

  • v (int, Tensor or iterable[int]) – Destination node IDs, v[i] gives the destination node for the i-th new edge.

  • data (dict[str, Tensor], optional) – Feature data of the added edges. The keys are feature names while the values are feature data.

  • etype (str or (str, str, str), optional) –

    The type names of the edges. The allowed type name formats are:

    • (str, str, str) for source node type, edge type and destination node type.

    • or one str edge type name if the name can uniquely identify a triplet format in the graph.

    Can be omitted if the graph has only one type of edges.


The graph with newly added edges.

Return type



  • If the end nodes of the given edges do not exist in g, dgl.add_nodes() is invoked to add those nodes. The node features of the new nodes will be filled with zeros.

  • For features in g but not in data, DGL assigns zero features for the newly added nodes.

  • For feature in data but not in g, DGL assigns zero features for the existing nodes in the graph.


The following example uses PyTorch backend.

>>> import dgl
>>> import torch

Homogeneous Graphs

>>> g = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 2])))
>>> g.num_edges()
>>> g = dgl.add_edges(g, torch.tensor([1, 3]), torch.tensor([0, 1]))
>>> g.num_edges()

Since u or v contains a non-existing node ID, the nodes are added implicitly.

>>> g.num_nodes()

If the graph has some edge features and new edges are added without features, their features will be filled with zeros.

>>> g.edata['h'] = torch.ones(4, 1)
>>> g = dgl.add_edges(g, torch.tensor([1]), torch.tensor([1]))
>>> g.edata['h']
tensor([[1.], [1.], [1.], [1.], [0.]])

You can also assign features for the new edges in adding new edges.

>>> g = dgl.add_edges(g, torch.tensor([0, 0]), torch.tensor([2, 2]),
...                   {'h': torch.tensor([[1.], [2.]]), 'w': torch.ones(2, 1)})
>>> g.edata['h']
tensor([[1.], [1.], [1.], [1.], [0.], [1.], [2.]])

Since data contains new feature fields, the features for old edges will be filled with zeros.

>>> g.edata['w']
tensor([[0.], [0.], [0.], [0.], [0.], [1.], [1.]])

Heterogeneous Graphs

>>> g = dgl.heterograph({
...     ('user', 'plays', 'game'): (torch.tensor([0, 1, 1, 2]),
...                                 torch.tensor([0, 0, 1, 1])),
...     ('developer', 'develops', 'game'): (torch.tensor([0, 1]),
...                                         torch.tensor([0, 1]))
...     })
>>> g.number_of_edges('plays')
>>> g = dgl.add_edges(g, torch.tensor([3]), torch.tensor([3]), etype='plays')
>>> g.number_of_edges('plays')