id() Getting the memory address
We don’t usually think about memory addresses, but in an environment where memory is limited, knowing which objects are using how much memory can help us develop a hardware friendly system.
github
- The jupyter notebook format file on github is here .
google colaboratory
- If you want to run it on google colaboratory here 003/003_nb.ipynb)
Author’s environment
! sw_vers
ProductName: Mac OS X
ProductVersion: 10.14.6
BuildVersion: 18G2022
Python -V
Python 3.7.3
a = [i ** 2 for i in range(100)].
id(a)
4506754184
Used to check if objects are identical.
a = [1,2,3].
b = a
print('a :',id(a))
print('b :',id(b))
a : 4506838024
b : 4506838024
Declarations of different variables with the same value will be assigned the same address.
a = 1
b = 1
print('a =',a)
print('b =',b)
print('same address')
print('a :',id(a))
print('b :',id(b))
print(id(a) == id(b))
print()
a = 1
b = 2
print('a =',a)
print('b =',b)
print('different addresses')
print('a :',id(a))
print('b :',id(b))
print(id(a) == id(b))
a = 1
b = 1
Same address
a : 4451820960
b : 4451820960
True
a = 1
b = 2
Different address
a : 4451820960
b : 4451820992
False.
Assigning creates a new object.
a = 1
print('a =',a)
print('a :',id(a))
print()
# Assign different values to a
a = 2
print('a =',a)
print('a :',id(a))
a = 1
a : 4451820960
a = 2
a : 4451820992
Arrays are passed by reference, so if the referent changes, so does the dereference.
a = [1,2,3].
b = a
print('a =',a)
print('b =',b)
print('a :',id(a))
print('b :',id(b))
print(id(a) == id(b))
print()
a[0] = 5
print('Change referrer too')
print('a =',a)
print('b =',b)
print('a :',id(a))
print('b :',id(b))
print(id(a) == id(b))
a = [1, 2, 3].
b = [1, 2, 3].
a : 4506837320
b : 4506837320
True
Change the referrer too
a = [5, 2, 3].
b = [5, 2, 3].
a : 4506837320
b : 4506837320
True
Use copy() to explicitly create another object.
from copy import copy
a = [1,2,3].
b = copy(a)
print('a =',a)
print('b =',b)
print('a :',id(a))
print('b :',id(b))
print(id(a) == id(b))
print()
a[0] = 5
print('a =',a)
print('b =',b)
print('a :',id(a))
print('b :',id(b))
print(id(a) == id(b))
a = [1, 2, 3].
b = [1, 2, 3].
a : 4505419144
b : 4505419400
False
a = [5, 2, 3].
b = [1, 2, 3] a : 4505419144
a : 4505419144
b : 4505419400
False