id
function in Python shows the memory location of a given object.x = 5.5
y = x
print(f"Location of x is {id(x)}")
print(f"Location of y is {id(y)}, the same as x")
Location of x is 4588908880 Location of y is 4588908880, the same as x
x
and y
, if we now set y=6.6, we create a new object, 6.6, and tag it with the variable named y
y = 6.6
print(f"Location of y is {id(y)}, now different than x above")
Location of y is 4588908720, now different than x above
import numpy as np
a = np.array([1,2,3,4])
b = a # try b = a.copy() instead
a[0] = 101325
print(b)
id(a), id(b)
[101325 2 3 4]
(4620964288, 4620964288)
a
and b
both tag the same list object.a[0] = 101325
, then b
appears to have also changed.a
and b
both tag the same object.a[0]
and b[0]
.a
and b
to refer to separate objects so that setting a[0]=101325
won't affect b
, the use b=a.copy()
a = [1,2,3,4]
print(f"id(a) = {id(a)}")
b = a.copy()
print(f"id(b) = {id(b)}, is different than a")
a[0] = 101325
print(f"setting a[0]= 101325")
print(f"b[0] hasn't changed: {b[0]}")
id(a) = 4362623648 id(b) = 4363030352, is different than a setting a[0]= 101325 b[0] hasn't changed: 1
a = np.array([1,2,3,4])
b = a*2 # assigns b to a new object array a*2; a is unchanged
a[0] = 101325 # b is unchanged
b
id(a), id(b)
(4764209600, 4764210080)
def f(x):
return "kittens"
print = f
print("101325")
'kittens'
2
(an integer) and tag it with variable x
.x
here is a global variable.f(x)
x=6
creates a new object 6
, and tags it with the local variable x
.x
to 2
, so we create a local x
tag that is bound to the object 6
.2
still exists and is still tagged by the global variable x
.x = 2 # 1. create integer object 2 tagged by x
#-----------------------------------
def f(x):
print("x top of func:", x, id(x))
x = 6 # 2A. create LOCAL tag x bound to different object 6
print("x end of func:", x, id(x))
#-----------------------------------
f(x) # 2. call the function
print("x final: ", x, id(x)) # 3. outer object x is unchanged
x top of func: 2 4555722544 x end of func: 6 4555722672 x final: 2 4555722544
myx
.x
.So, you can change mutable objects through the function argument list, without using a return
statement.
def f(x): # 3. same object tagged with variable name x
x[1] = 6 # 4. change value of element in same object
#---------------------
myx = [2,2] # 1. define list object tagged by variable name myx
f(myx) # 2. call function: changes object, prints address
print(myx) # 5. print values: list is still changed outside
[2, 6]