+ 2
Why does this return same memory address?
a = 5 b = 5 print(id(a)) print(id(b)) print(id(5))
2 Answers
+ 6
Both variables a and b reference to the same object of class int - 5.
Python cashes small integers to improve performance and memory consumption.
To see this you can run the next code:
import sys
a = 5
print(sys.getrefcount(5)) # some count
b = 5
print(sys.getrefcount(5)) # count + 1
+ 1
Read about immutability in python..
Edit:
https://www.tutorialspoint.com/What-is-immutable-in-Python