Num py - No copy at all
The provided Python code snippet demonstrates the concept that simple assignments do not create copies of objects or their data. Here's a breakdown:
An array 'a' is created using NumPy with some values arranged in a 2D array format.
Another variable 'b' is assigned the same reference as 'a', meaning 'b' now points to the same ndarray object as 'a'.
The comparison 'b is a' checks if 'b' and 'a' refer to the same object, which returns True.
The 'id()' function in Python returns the unique identifier of an object. The 'id(a)' and 'id(x)' (inside the function 'f') both print the same identifier, confirming that 'a' and 'x' refer to the same object.
The 'f(a)' call inside the function prints the identifier of 'a', which matches the identifier of 'a' outside the function, indicating that 'a' is passed to the function by reference.
Overall, the code demonstrates how assignments and function calls work with mutable objects like NumPy arrays in Python, where no copies are made, and variables reference the same underlying object.
No copy at all
Simple assignments make no copy of objects or their data.
>>> a = np.array([[ 0, 1, 2, 3],
... [ 4, 5, 6, 7],
... [ 8, 9, 10, 11]])
>>> b = a # no new object is created
>>> b is a # a and b are two names for the same ndarray object
True
Python passes mutable objects as references, so function calls make no copy.
>>> def f(x):
... print(id(x))
...
>>> id(a) # id is a unique identifier of an object
148293216 # may vary
>>> f(a)
148293216 # may vary
Comments
Post a Comment