Sobes.tech
Junior — Middle

What are the ways to create a copy of an object in programming?

sobes.tech AI

Answer from AI

In programming, an object copy can be created in several ways:

  1. Shallow copy — a new object is created, but nested objects inside it are not copied, only referenced.
  2. Deep copy — a fully independent copy of the object is created along with all nested objects.
  3. Serialization and deserialization — the object is serialized into a string or bytes, then restored, which results in a copy.
  4. Copy constructor or clone method — some languages have special methods or constructors for creating copies.

Example in Python:

import copy

original = {'a': 1, 'b': [2, 3]}
shallow = copy.copy(original)  # shallow copy
deep = copy.deepcopy(original)  # deep copy

shallow['b'].append(4)
print(original['b'])  # [2, 3, 4] — changed because the list is shared
print(deep['b'])     # [2, 3] — unchanged
What are the ways to create a copy of an object in… - sobes.tech