In [1]:
a = 5.
print(id(a))
b = 5.
print(id(b))
If you assign a variable, the ID is passed. This means that the same object has just only two different names, but it is still the same object. This saves memory.
In [5]:
c = a
print id(c)
print c is a
print c == a
print b == a
print b is c
In [6]:
print(c)
print c is a
c = 4.
print(c)
print(a)
print c is a
In [ ]:
# let's do some changes
c += 2.
print(c)
print c is a
In [ ]:
print c
c -= 2.
print(c, a)
print c is a
print c == a
In [7]:
s1 = 'hello'
s2 = 'world'
print(s1 is s2)
print(s1 == s2)
In [ ]:
s3 = s1
print s1 is s3
In [8]:
s4 = 'hello'
print(s1 is s4) # note that even a new variable is generated, while its contents already exists, just a pointer is used
print(s1 == s4)
print(id(s1),id(s4))
In [ ]:
s4 += ' geography'
print(s4)
print(id(s4))
print(s4 is s1)
In [16]:
import numpy as np # we talk about numpy later today
A = np.array([[1, 2], [3, 4]])
A
Out[16]:
In [17]:
B=A*1. # copy, deepcopy
B
Out[17]:
In [18]:
print id(A), id(B)
In [19]:
B[0,0]=10.
B
Out[19]:
Note what happened to A now ...
In [20]:
A
Out[20]:
In [14]:
C = A
C[1,1] = 77.
In [15]:
B
Out[15]:
In [ ]:
def foo(a,b):
print(a + ' ' + b)
a = 'Hello'
b = 'World'
foo(a,b)
In [ ]:
def foo1(a,b):
c = a+b
a = 'Munich'
print(c)
foo1(a,b)
print(a) # the original variable was unchanged
Remember: Variables have a scope; e.g. within a functionmm
In [ ]: