Is copy.copy() is different from assignment in python?

Total Views : 2,296 , Today Views : 1 

Assignment statements in Python do not copy objects, they create bindings between a target and an object. When we use the = operator, the user can assume that we are creating a new object; however, this is not the case. It only creates a new variable which shares the original object’s relation. Sometimes for collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other.

Example 1: Copy through using Variables:

A sample Pandas series is generated and copied into a new variable using assignment operator (=) in this example. Following that, several modifications are made to the new data, which is then compared to the old data.

Is copy.copy() is different from assignment in python 1

The changes made to new data are also mirrored in the old data, as seen in the output image, because the new variable was only a pointer to the old one.

Is copy.copy() is different from assignment in python 2

copy.copy():- Copy will create a new object in memory, and then assign the variable to that using a technique called as Shallow copy.

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.”

Example 2: using copy.copy() function

A sample Pandas series is generated and copied into a new variable using copy.copy() function in this example. Following that, several modifications are made to the new data, which is then compared to the old data.

Is copy.copy() is different from assignment in python 3

The changes in new data are independent of the changes in old data, as seen in the output image.

Is copy.copy() is different from assignment in python 4

Leave a Reply

Your email address will not be published. Required fields are marked *