print memory address of Python variable [duplicate] print memory address of Python variable [duplicate] python python

print memory address of Python variable [duplicate]


id is the method you want to use: to convert it to hex:

hex(id(variable_here))

For instance:

x = 4print hex(id(x))

Gave me:

0x9cf10c

Which is what you want, right?

(Fun fact, binding two variables to the same int may result in the same memory address being used.)
Try:

x = 4y = 4w = 9999v = 9999a = 12345678b = 12345678print hex(id(x))print hex(id(y))print hex(id(w))print hex(id(v))print hex(id(a))print hex(id(b))

This gave me identical pairs, even for the large integers.


According to the manual, in CPython id() is the actual memory address of the variable. If you want it in hex format, call hex() on it.

x = 5print hex(id(x))

this will print the memory address of x.


There is no way to get the memory address of a value in Python 2.7 in general. In Jython or PyPy, the implementation doesn't even know your value's address (and there's not even a guarantee that it will stay in the same place—e.g., the garbage collector is allowed to move it around if it wants).

However, if you only care about CPython, id is already returning the address. If the only issue is how to format that integer in a certain way… it's the same as formatting any integer:

>>> hex(33)0x21>>> '{:#010x}'.format(33) # 32-bit0x00000021>>> '{:#018x}'.format(33) # 64-bit0x0000000000000021

… and so on.

However, there's almost never a good reason for this. If you actually need the address of an object, it's presumably to pass it to ctypes or similar, in which case you should use ctypes.addressof or similar.