I am trying to make a graph from a list of tuples stored in a variable. I found G.add_edges_from(e)
for making graph using list of tuples. but the problem is that this does not work and when i try to for example print the graph it returns None
. I appreciate answers that solve my problem. I use the code below to make the graph:
import networkx as nx
e = [(1,2),(1,3),(2,3)]
G = nx.Graph()
g1 = G.add_edges_from(e)
print(g1)
Update: I testes this code but again give None when trying to print:
e = [[(1,2),(1,3),(2,3)],[(10,20),(10,30),(20,30)]]
graph_list = []
for i in e:
graph_list.append(nx.Graph().add_edges_from(i))
print(graph_list[0].nodes)
Let's break it down shall we?
You assigned a list of edges in e, then you made a graph with G.
However, your issue is you're trying to assign g1 to what the method add_edges_from
returns (which is None).
What you actually want is something like this:
import networkx as nx
e = [(1,2),(1,3),(2,3)]
G = nx.Graph()
G.add_edges_from(e)
print(G)
Since the add_edges_from
method returns None
it is working as intended, you should try printing your original graph instead. I hope this helps and clarifies things for you!
Edit: If you insist on just using the list of tuples, you can just do away with variables. Use lists to store graph objects instead, keep storing them in a loop as such:
e = [[(1,2),(1,3),(2,3)],[(10,20),(10,30),(20,30)]]
graph_list = []
for i in e:
G = nx.Graph()
G.add_edges_from(i)
graph_list.append(G)
print(graph_list[0].nodes)
print(graph_list[1].nodes)
Then you can use indices to get each specific graph you make (which would be stored separately in the list)
Or you might want to start dumping each graph in a json file ([answered here] (Method to export networkx graph to json graph file?))
Which can solve your RAM issue