Saturday, November 16, 2024
Google search engine
HomeLanguagesHow to get the memory address of an object in Python

How to get the memory address of an object in Python

In Python, everything is an object, from variables to lists and dictionaries everything is treated as objects. In this article, we are going to get the memory address of an object in Python. 

Method 1: Using id()

We can get an address using the id() function. id() function gives the address of the particular object.

Syntax:

id(object)

where the object is the data variables.

Example: Python program to get the address of different objects

Python3




# get id of list
a = [1, 2, 3, 4, 5]
print(id(a))
  
# get id of a variable
a = 12
print(id(a))
  
# get id of tuple
a = (1, 2, 3, 4, 5)
print(id(a))
  
# get id of a dictionary
a = {'a': 1, 'b': 2}
print(id(a))


Output:

140234866534752

94264748411744

140234904267376

140234866093264

Method 2: Using c_int, addressof modules

ctypes is a foreign function library for Python. It provides C compatible data types and allows calling functions in DLLs or shared libraries.

Syntax:

addressof(c_int(object))

where object is the data variables

Example: Python program to get the memory address of  a variable

Python3




# import addressof and c_int modules 
# from ctypes module
from ctypes import c_int, addressof
  
# get memory address of variable
a = 44
print(addressof(c_int(a)))


Output:

140234866278064

It is also possible to get memory addresses in hexadecimal format. Here we will call the hex(address) function, to convert the memory address to hexadecimal representation.

Syntax:

hex(id(object))

where,

  • hex() is the memory hexadecimal representation to the address
  • id is used to get the memory of the object
  • object is the data

Example: Python program to get the memory address in hexadecimal representation.

Python3




# get id of list in hexadecimal representation
a = [1, 2, 3, 4, 5]
print(hex(id(a)))
  
# get id of a variable in hexadecimal 
# representation
a = 12
print(hex(id(a)))
  
# get id of tuple in hexadecimal 
# representation
a = (1, 2, 3, 4, 5)
print(hex(id(a)))
  
# get id of a dictionary in hexadecimal 
# representation
a = {'a': 1, 'b': 2}
print(hex(id(a)))


Output:

0x7fba9b0ae8c0

0x5572da858b60

0x7fba9f3c4a10

0x7fba9b05b8c0

RELATED ARTICLES

Most Popular

Recent Comments