Skip to content

Instantly share code, notes, and snippets.

@rcassani
Created August 17, 2021 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rcassani/bcdeafca95a85b8be40f61e77660e537 to your computer and use it in GitHub Desktop.
Save rcassani/bcdeafca95a85b8be40f61e77660e537 to your computer and use it in GitHub Desktop.
Python mutability numpy array demo
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