Created
August 17, 2021 14:28
-
-
Save rcassani/bcdeafca95a85b8be40f61e77660e537 to your computer and use it in GitHub Desktop.
Python mutability numpy array demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
# How NOT to do it!!! | |
x = np.zeros([2,2]) # NumPy array, is mutable | |
print(id(x)) # ID for x | |
a = x # a is not a copy of x, it is the same variable in memory | |
print(id(a)) # ID of a == ID of x | |
x[0,0] = 1 # Updating values in x | |
b = x # b is not a copy of x, it is the same variable in memory | |
print(id(a)) # ID of a == ID of x | |
print(x) | |
print(a) | |
print(b) | |
# How to do it | |
x = np.zeros([2,2]) # NumPy array, is mutable | |
print(id(x)) # ID for x | |
a = x * 1 # a is x multiplied by 1, thus it is not the same variable in memory | |
print(id(a)) # ID of a != ID of x | |
x[0,0] = 1 # Updating values in x | |
b = x * 1 # b is x multiplied by 1, thus it is not the same variable in memory | |
print(id(a)) # ID of a != ID of x | |
print(x) | |
print(a) | |
print(b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment