What is the difference between shallow copy and '=' in Python? [duplicate] - python

This question already has answers here:
What is the difference between shallow copy, deepcopy and normal assignment operation?
(12 answers)
Closed 3 years ago.
x = Object1
b = Object2
What is the difference between
import copy
x = b
x = copy.copy(b)

Assignment statements in Python do not copy objects, they create bindings between a target and an object
copy doc #python.org
Thus if you really want to have the same object twice without any bindings between you can use the copy package.

Related

Why does the remove() Method also Removes from Copies and How to Work Around it? [duplicate]

This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 2 years ago.
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?
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:
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.
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.

Why does Python create a link between the input of a function and the actual parameter instead of a copy? [duplicate]

This question already has answers here:
Why can a function modify some arguments as perceived by the caller, but not others?
(13 answers)
List of lists changes reflected across sublists unexpectedly
(17 answers)
Closed 2 years ago.
Suppose I have a function which returns a modified version of an input, say a sorting algorithm:
def insertion_sort(listToSort):
for itemToSort in range(1, len(listToSort)):
for i in range(itemToSort, 0, -1):
if listToSort[i] < listToSort[i-1]:
listToSort[i], listToSort[i-1] = listToSort[i-1], listToSort[i]
else:
break
Usually I'd expect that I need to return the new modified version. But in Python, it seems like actual parameters are not a copy of the input, but instead a "link" to the input. This is different from other languages I've worked with (C#, C++), is there a reason this choice was made or was it an arbitrary one?

List of class instances in python [duplicate]

This question already has answers here:
Python copy.deepcopy() function not working properly [duplicate]
(3 answers)
How to avoid having class data shared among instances?
(7 answers)
Closed 5 years ago.
I am new to python, and more used to C++. I want to create a list of instances and did the following:
from copy import deepcopy
class C:
c1=""
c2=""
Cs=[]
C.c1="Hello"
C.c2="World"
Cs.append(deepcopy(C))
C.c1="Why"
C.c2="this?"
Cs.append(deepcopy(C))
for c in Cs:
print (c.c1, c.c2)
I expected the following output:
Hello World
Why this?
but got:
Why this?
Why this?
Why is the deep copy not working?
there is only one (static in the Java/C++ sense) copy of the c1 and c2 variables. Read https://www.toptal.com/python/python-class-attributes-an-overly-thorough-guide and sprinkle more selfs in your code to fix it.

How to save a "self" variable in python? [duplicate]

This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 7 years ago.
In python, inside a class, it appears that when I save a "self" variable into another one, if I edit the new variable, the "self" is also edited:
undropped_lines = self.flagged_lines
print self.flagged_lines
del undropped_lines[0]
print self.flagged_lines
How should one avoid this trait in the code?
This is because lists are mutable and when you say undropped_lines = self.flagged_lines you are just pointing a new name at the same instance.
If you want a copy use undropped_lines = self.flagged_lines[:]
This is because undropped_lines and self.flagged_lines are pointing to the same data. Think of it as two different "names" pointing to the same entity.
You can get around this by creating a shallow copy of the list when assigning to undropped_lines. Something like:
undropped_lines = list( self.flagged_lines )

Python make list copy, not reference [duplicate]

This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 8 years ago.
I have list of int's called board in python code. I wan't to know, if it was modified, so I have code
self.oldboard = list(self.board)
#here is board modified, if it is possible
if not self.oldboard == self.board:
#this should execute only when board was modified
But oldboard is always equals to board, when I modify board, it modifies oldboard. How to make oldboard just copy of board, not reference?
When copying lists by the slice method (analogous to what you're currently doing):
new_list_copy = old_list[:]
you'll only get a "shallow" copy of the contents. This isn't suitable for lists that contain lists ("nested lists").
If you're trying to copy a nested list, a Pythonic solution is to use deepcopy from the copy module:
import copy
new_list_copy = copy.deepcopy(old_list)
Integers are immutable. I would recommend you familiarize yourself with the notions of shallow and deep copy operations, which you can find in the Python Docs here . In your case you most likely need to use deepcopy, as I would guess that you have several nested lists.

Categories

Resources