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:
            G.add_edge(node1, node2)


It's probably very inefficient because it sees every node twice and also adds self-loops.
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:
    G.add_edges_from(itertools.product(node_tuple, node_tuple))


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.