print memory address of Python variable [duplicate]

Each Answer to this Q is separated by one/two green lines.

How do I print the memory address of a variable in Python 2.7?
I know id() returns the ‘id’ of a variable or object, but this doesn’t return the expected 0x3357e182 style I was expecting to see for a memory address.
I want to do something like print &x, where x is a C++ int variable for example.
How can I do this in Python?

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


For instance:

x = 4
print hex(id(x))

Gave me:


Which is what you want, right?

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

x = 4
y = 4
w = 9999
v = 9999
a = 12345678
b = 12345678
print 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 = 5
print 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)
>>> '{:#010x}'.format(33) # 32-bit
>>> '{:#018x}'.format(33) # 64-bit

… 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.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.