Python id- When x is 3, x and 3 have the same id
id is the identity of an object. We can get an object id by
id built-in function.
a = 3 b = a i = id(a) j = id(b) print(i) # 4467476736 print(j) # 4467476736
id represents the memory address of an object
The id of
a is 4467476736. Every time running Python program, the value changes. It's important the ids
b are the same.
The next code represents the essence of Python objects.
a = 3 b = a print(id(3)) # 4385929472 print(id(a)) # 4385929472 print(id(b)) # 4385929472
b have the same id.
The same values has the same id
print(id(3)) # 4308912384 a = 1 b = 2 c = a + b print(id(c)) # 4308912384
Every time running Python, the id of
3 changes but the id of
3 and one of
c, whose value is 3, are the same.
You may think
c is stored in the other memory and both
c are completely different objects. But Python shows both share the same address.
Object in function
def f(n): print('id(n) =', id(n)) m = n + 2 print('id(m) =', id(m)) return m print('id(1) =', id(1)) print('id(3) =', id(3)) a = 1 b = f(a) # id(1) = 4401371328 # id(3) = 4401371392 # id(n) = 4401371328 # id(m) = 4401371392
The above shows the id of
1 and the id of
a in the function are the same.
m have the same id.
a = [1, 2, 3] b = [1, 2, 3] print(id(a)) # 4513771904 print(id(b)) # 4513772736
We think a and b are equal so the addresses of them are the same. But it is not true. They are completely different.
But as implied in the following code, the same integers have the same id.
a = [1, 2, 3] b = [1, 2, 3] print(id(a)) # 4513771904 print(id(b)) # 4513772736 print(id(a)) # 4535740608 print(id(b)) # 4535740608