Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print memory address of Python variable [duplicate]

People also ask

How do you print a memory address of a variable in Python?

Method 1: Find and Print Address of Variable using id() We can get an address using id() function, id() function gives the address of the particular object. where, object is the data variables. Here we are going to find the address of the list, variable, tuple and dictionary.

How do I find the memory address in Python?

In Python, you don't generally use pointers to access memory unless you're interfacing with a C application. If that is what you need, have a look at the ctypes module for the accessor functions. Show activity on this post. Show activity on this post.

How do you print a memory address of a variable?

To print the memory address, we use '%p' format specifier in C. To print the address of a variable, we use "%p" specifier in C programming language.


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

hex(id(variable_here))

For instance:

x = 4
print 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 = 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)
0x21
>>> '{:#010x}'.format(33) # 32-bit
0x00000021
>>> '{:#018x}'.format(33) # 64-bit
0x0000000000000021

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