-1

I've been experiencing a quite strange error while using python.

I have a variable named graph, which is a list of lists and I'm modifying and a variable copy which is supposed to "remember" the original value of graph.

However, when I apply the remove() method to graphthe value of copy also changes!

Here is a reproducible example:

graph = [[1,2],[2,3],[3,1]]
copy = graph
print("graph =" + str(graph))
print("copy =" + str(copy))
graph[0].remove(2)
print("graph =" + str(graph))
print("copy =" + str(copy))

Does anyone know how to deal with this issue?

Ariel Serranoni
  • 119
  • 1
  • 5

1 Answers1

1

You're not creating a copy, you should use copy library which creates a new object which is a copy of the old object, you have two option:

  1. Shallo Copy: A shallow copy creates a new object which stores the reference of the original elements. So, a shallow copy doesn't create a copy of nested objects, instead it just copies the reference of nested objects.
  2. Deep Copy: A deep copy creates a new object and recursively adds the copies of nested objects present in the original elements.

Example of Shallow Copy:

import copy

graph = [[1,2],[2,3],[3,1]]
copied_graph = copy.copy(graph)

Example of Deep Copy:

import copy

graph = [[1,2],[2,3],[3,1]]
copied_graph = copy.deepcopy(graph)

In this case, if you use Shallow Copy you can add another element to your graph list and it wont be changed in copied_graph, but if you change one of the lists inside the graph list (nested objects) it will change in copied_graph and if you also want to prevent this, you should use Deep Copy.

SMMousaviSP
  • 624
  • 7
  • 23
  • Can I do the same thing just without any library? My code is originally for a competitive programming problem, so I can't use any libs :( – Ariel Serranoni Nov 13 '20 at 17:49
  • @ArielSerranoni It's a standard library; I participated in ACM-ICPC, trust me, there's no problem using a standard library in a programming contest. In some programming languages, you can't print anything without importing/including a standard library. – SMMousaviSP Nov 13 '20 at 17:51
  • That worked, thank you so much! I just didn't know the library you mentioned – Ariel Serranoni Nov 13 '20 at 17:58
  • @ArielSerranoni You're welcome, I added some extra information, please read it. – SMMousaviSP Nov 13 '20 at 18:01