copy
Syntax
copy(obj)
Arguments
obj can be of any data type.
Details
Returns a shallow copy of obj. A shallow copy only copies the outer structure, while inner elements (sub-objects) still share references with the original object.
The difference between copy
(shallow copy) and
deepCopy
(deep copy) is most evident when dealing with
nested structures such as tuples or dictionaries of type ANY:
copy
only duplicates the top-level structure, while sub-objects retain shared references (i.e., the sub-object addresses remain unchanged).deepCopy
recursively copies all sub-objects, ensuring fully independent references.
Examples
Example 1. Copy a vector
x = 1 2 3
a = x.copy()
b = x.deepCopy();
print constantDesc(x[0]).address // 000000000dd3d640
print constantDesc(a[0]).address // 000000000cb5a4c0
print constantDesc(b[0]).address // 000000000de92c20
Example 2. Copy a tuple
x = ([[1, 2], [3, 4]], "a")
a = x.copy()
b = x.deepCopy();
print constantDesc(x[0]).address // 000000000c7ce880
print constantDesc(a[0]).address // 000000000c7ce880
print constantDesc(b[0]).address // 000000000c89be00
Example 3. Copy an ANY dictionary
y = dict(`A`B`C, (1 2, 3 4, 5 6))
c = y.copy()
d = y.deepCopy();
print constantDesc(y[`A]).address // 000000000c88c450
print constantDesc(c[`A]).address // 000000000c88c450
print constantDesc(d[`A]).address // 000000000c7cde00