COMPARE
COMPARE
COMPARE
1) Aliasing:-
Aliasing shares the same memory location and modifies the original array if any of the
aliases are modified.
It does not create a new copy of the array but rather creates a new variable that points to
the same memory location. As a result, changes made to one alias will be reflected in all
aliases, as they all refer to the same data.
Aliasing is not a specific copying method but rather a behavior that can occur unintentionally
if you are not careful when creating new variables from existing arrays.
reference is copied rather than copying the actual value.
Example:-
list1 = [1, 2, 3]
list2 = list1
list1[0] = 0
print(list2)
Output:
[0, 2, 3]
2) shallow copy:-
A shallow copy means constructing a new collection object and then populating it with
references to the child objects found in the original. In essence, a shallow copy is only one
level deep. The copying process does not recurse and therefore won’t create copies of the
child objects themselves.
A shallow copy creates a new array object but only copies the top-level elements from the
original array. It does not recursively copy the elements within nested arrays. As a result, the
new array shares the references to the same objects as the original array for elements that
are themselves arrays.
Example:-
import copy
old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_list = copy.copy(old_list)
print("Old list:", old_list)
print("New list:", new_list)
Output:
Old List: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
ID of Old List: 140673303268168
3) deep copy
A deep copy creates a completely independent new array object, including all the elements
within nested arrays. It recursively copies all the data, so changes made to the deep copy
will not affect the original array or any nested arrays, and vice versa.
deep copy makes the copying process recursive. It means first constructing a new collection
object and then recursively populating it with copies of the child objects found in the
original. Copying an object this way walks the whole object tree to create a fully
independent clone of the original object and all of its children
Example:-
import numpy as np
original_array = np.array([1, 2, [3, 4]])
deep_copied_array = original_array.copy()
deep_copied_array[0] = 100
deep_copied_array[2][0] = 300
print(original_array)
Output:
[1 2 list([3, 4])]
shallow copy:-
In some cases, we may want to create a copy of a value so that two different pieces of code
see different copies of the same value. This allows one to be manipulated differently from
the others.
deep copy
The alternative to this is to perform a deep copy of the object. This is where we copy each
field from the original to the copy, but as we do so, we perform a deep copy of those instead
of just copying the references: