Junior — Middle
Selgitage, mis on objekti pindaliku kopeerimine Pythonis ja kuidas see erineb sügavast kopeerimisest.
sobes.tech AI
Vastus AI-lt
Shallow copy in Python creates a new object, but the nested objects inside it are not copied, only references to them are copied. That means if the object contains mutable nested structures (like lists, dictionaries), they will be shared between the original and the copy.
Deep copy creates a new object and recursively copies all nested objects, creating a completely independent copy.
Example:
import copy
original = [1, [2, 3]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
shallow[1].append(4)
print(original) # Outputs: [1, [2, 3, 4]] — the nested list has changed in the original too
print(deep) # Outputs: [1, [2, 3]] — the deep copy remains unchanged
Therefore, shallow copy is suitable when nested objects do not change, and deep copy when full independence of the copy from the original is needed.