How Do You Use the .copy() Feature in Python?

Problem scenario
You want to use the copy feature in Python. What do you do?

Solution
To see the different types of copying, use a mutable object such as a list. Here is an example:

import copy

var1 = [1, 2, 3, 4]
shallow_copy = var1
deep_copy = copy.deepcopy(var1)
var1.append(999999999999)

print()
print(shallow_copy)
print(" --- Shallow copy above and deep copy below ---.")
print(deep_copy)

For most (or perhaps all) intents and purposes, you cannot shallow copy a string. You can shallow copy a list or other mutable object. This is how you can use the .copy() feature with a string (but notice how the effect of deep copying takes place):

import copy

var1 = "a sample string"
shallow_copy = var1
deep_copy = copy.deepcopy(var1)
var1 = var1 + " some extra text added later on -----------------------------------------"

print()
print(shallow_copy)
print(" --- Shallow copy above and deep copy below ---.")
print(deep_copy)

If you cannot use the copy module (e.g., use "import copy") see this PoStInG: Why in Python Does a Variable Copy Get Changed when You Change Its Source?

Leave a comment

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