3

I have a python-igraph and need to make two copies of it and change each of the copies without changing the other one. Right now I am doing it like this:

copy1 = fullGraph
copy2 = fullGraph

But it seems that this is not the correct way of doing it since whatever I change in copy1, the same thing happen to copy2 (like deleting an edge). I was wondering what is the best way to make a copy of the main graph.

Thanks

ahajib
  • 12,838
  • 29
  • 79
  • 120

2 Answers2

5

Assign statements do not copy objects in Python. You might want to use copy.deepcopy() function.

More details about copy.shallow() and copy.deepcopy() can be found in this answer

Also Graph objects have inherited copy method which makes a shallow copies. You can use it like:

copy1 = fullGraph.copy()
copy2 = fullGraph.copy()
Stefan
  • 919
  • 2
  • 13
  • 24
Konstantin
  • 24,271
  • 5
  • 48
  • 65
0

A graph objects has a copy method which creates a shallow copy. Use it like:

myGraphShallowCopied = myGraph.copy()

Note that the graph is duplicated, but objects stored in the graph are not. This means, that if you change a graph, only the copy (or the original) get changed. If you change an object in the graph, it will change for both the copied graph as the original graph as they reference the same object.

If you want a true copy you can use copy.deepcopy() like:

from copy import deepcopy
myGraphDeepCopied = deepcopy(myGraph)

Note that this can be (depending on the objects stored in the graph) much slower than creating a shallow copy.

A clear explanation between the difference of a shallow and deepcopy can be found here in this answer.

Stefan
  • 919
  • 2
  • 13
  • 24