1

For example:

g1 = nx.DiGraph()    
g1.add_edge(1,1,w = 1)    
g1.add_edge(1,2,w = 1)    

g1.add_edge(1,3,w = 2)    
g1.add_edge(2,2,w = 2)   

g2 = g    
print g2.predecessors(2)  #[1, 2]

g1.remove_node(1)    
print g2.predecessors(2)  #[2]

when I remove the node 1 in g1, g2 is also influenced. I want to create the same graph g2 as g1 but then when I make changes to g1, g2 will not change. How can I do that? Thanks!!!

MB-F
  • 22,770
  • 4
  • 61
  • 116
Jie
  • 11
  • 1

1 Answers1

1

Call method copy() on the graph so you don't make a reference:

In [41]:
g1 = nx.DiGraph()    
g1.add_edge(1,1,w = 1)    
g1.add_edge(1,2,w = 1)    
​
g1.add_edge(1,3,w = 2)    
g1.add_edge(2,2,w = 2)   
​
g2 = g1.copy()    
print( 'before g2', g2.predecessors(2) ) #[1, 2]
​
g1.remove_node(1)    
print ('after g2', g2.predecessors(2))  #[2]
print ('g1 graph ', g1.predecessors(2))  #[2]

before g2 [1, 2]
after g2 [1, 2]
g1 graph  [2]

You can see that graph g2 is unmodified whilst g1 has had a node removed

EdChum
  • 376,765
  • 198
  • 813
  • 562