When to Use copy() or deepcopy():

If you want to create an independent copy of mutable objects (like lists, dictionaries), use the following:

  1. Shallow Copy (copy):
    • Creates a new object but only copies the references of nested mutable elements.
    • Changes to nested objects reflect in the copy.
    Example:pythonCopy codeimport copy original = [1, [2, 3]] shallow = copy.copy(original) shallow[1][0] = 99 print(original) # Output: [1, [99, 3]]
  2. Deep Copy (deepcopy):
    • Creates a new object and recursively copies all nested objects. Changes in the copied object do not affect the original.
    Example:pythonCopy codeimport copy original = [1, [2, 3]] deep = copy.deepcopy(original) deep[1][0] = 99 print(original) # Output: [1, [2, 3]]

Summary:

  • Immutable objects like strings, integers, and tuples don’t require explicit copying because they can’t be modified.
  • Mutable objects like lists, dictionaries, and sets require careful handling if you need independent copies. Use copy.copy() or copy.deepcopy() when appropriate.

examples:

import copy
original = [1, [2, 3]]
shallow = copy.copy(original)
shallow[1][0] = 99
print(original)  # Output: [1, [99, 3]]

or_l = [1, [2, 3]]
shal_l = or_l
shal_l[1][0] = 99
print(or_l) 

or_dic = {"name":"Anne", "age":12}
shal_dic = or_dic
or_dic['name'] = "Test"
print(or_dic) 

Output:

[1, [99, 3]]
[1, [99, 3]]
{'name': 'Test', 'age': 12}

Leave a Reply

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

Deprecated: htmlspecialchars(): Passing null to parameter #1 ($string) of type string is deprecated in /var/www/html/wp-includes/formatting.php on line 4720