Some words on equality

A variable in python stores the reference to a register in the memory, not the actual value. Each variable has a unique id.


In [1]:
a = 5.
print(id(a))
b = 5.
print(id(b))


42661648
42661576

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


42661648
True
True
True
False

In [6]:
print(c)
print c is a
c = 4.
print(c)
print(a)
print c is a


5.0
True
4.0
5.0
False

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

Remember

  • The is function checks if the ID of two objects are the same.
  • The = operator checks if the numerical value is the same

How is it for strings?


In [7]:
s1 = 'hello'
s2 = 'world'
print(s1 is s2)
print(s1 == s2)


False
False

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))


True
True
(140406335508912, 140406335508912)

In [ ]:
s4 += ' geography'
print(s4)
print(id(s4))
print(s4 is s1)

Always be aware that an assignment might be just a pointer!


In [16]:
import numpy as np # we talk about numpy later today
A = np.array([[1, 2], [3, 4]])
A


Out[16]:
array([[1, 2],
       [3, 4]])

In [17]:
B=A*1.   # copy, deepcopy
B


Out[17]:
array([[ 1.,  2.],
       [ 3.,  4.]])

In [18]:
print id(A), id(B)


140406239478528 140406239477888

In [19]:
B[0,0]=10.
B


Out[19]:
array([[ 10.,   2.],
       [  3.,   4.]])

Note what happened to A now ...


In [20]:
A


Out[20]:
array([[1, 2],
       [3, 4]])

In [14]:
C = A
C[1,1] = 77.

In [15]:
B


Out[15]:
array([[10,  2],
       [ 3, 77]])

Where does it matter in particular? Working with functions


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 [ ]: