# Populate a networkx graph with tuples of varying lengths

I've got a list with tuples of variable length containing nodes, out of which I want to build a network:

node_list = [("one", "two"), ("eins", "zwei", "drei"),
("un", "deux", "trois", "quattre"), ("two", "zwei", "deux")]


Each tuple represents a subgroup in the network. I want to add each node with edges to any other member of the same tuple.

It is straightforward to use .add_edges_from(), which only expects a tuple with two nodes. For a tuple with three entries one would have to write .add_edges_from(("eins", "zwei"), ("eins", "drei"), ("zwei", "drei")). Tuples with four members require even more code.

Now I am looking for the most efficient way to populate a network given a list like node_list. My idea is:

import networkx as nx

G = nx.Graph()
for node_tuple in node_list:
for node1 in node_tuple:
for node2 in node_tuple:


It's probably very inefficient because it sees every node twice and also adds self-loops.

• Wouldn't this also create edges from each node to itself? Is that intended? Jun 19 '15 at 17:57
• It is. Simply populating with nodes is easy, but the edges make the network. Jun 19 '15 at 18:41

Tuples of varying lengths are a bit unusual. Perhaps those would be better as lists instead.

itertools is your friend. You can write, equivalently:

import itertools

G = nx.Graph()
for node_tuple in node_list:

If you want to list each pair of nodes just once instead of twice, and including self-edges use itertools.combinations_with_replacement(node_tuple, 2) instead.
• combinations will omit the self-edges: you need combinations_with_replacement Jun 19 '15 at 21:32
• combinations_with_replacement() did the trick. It's also good to know that there is combinations, in case one wants self-edges. Jun 20 '15 at 10:57