1

I declared two variables in Python 3 and tried printing their memory addresses as:

num1 = 1
num2 = 1
print(hex(id(num1)))
print(hex(id(num2)))

turns out that both the addresses are the same. Why is it so unlike C and C++ where every variable has a unique memory address.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Himanshu Negi
  • 17
  • 1
  • 4
  • Your question has been closed as a dup because this particular example is a bit of a special case (in the reference CPython implementation at least). But there's more to it actually - Python's variables are totally different from C/C++ ones, they are not symbolic names for memory locations, but key=>value pairs where the key is the name and the value the object the name is bound to. This is very clearly explained in [this excellent article](https://nedbatchelder.com/text/names.html) that you definitly want to read. – bruno desthuilliers Apr 17 '20 at 05:29

2 Answers2

3

Please read the answer here: https://stackoverflow.com/a/15172182/8733066

The python interpreter doesn't need tho save the value 1 multiple times because int is immutable. So all variables with the value four point to the same memory location.

bb1950328
  • 1,403
  • 11
  • 18
-4

Because that's how Python works. Everything is an object. Every number is an object. Every different string is an object. True and False are objects.

Andy Lester
  • 91,102
  • 13
  • 100
  • 152