Find the memory Address of a variable in Python

I am going to discuss ‘How to find the memory address of a variable’ in Python. Here I will give you a detailed explanation to find the address of variables.

Finding the Address of a Variable using  id() in Python

Let’s consider a person P lives in Kolkata, if we want to get the address of P, it will be Kolkata.

  • First of all, we can find the address of a variable using the id function.
  • This function returns an integer that indicates the virtual address of that variable.

For example

var1 = 10
var2 = 12
  • As a result above 10 digits decimal value gives the memory reference of variables var1 and var2. You may get the different value of address based on your system.
  • You can also do the same for finding the address similarly for a float, string, function or an object. Because when you initialize a variable compiler seems to reserve the memory space for them on a different address value.
  • Below given an example that gives the address of function sum.
def sum(var1,var2):
    return var1+var2
print("Address of funtion sum: ",id(sum))
Address of funtion sum: 55575944

⇒You can use id() with class object also it will give the reference of that object.

  • Furthermost above all address is Integer but you may saw many times that the memory address is written in hexadecimal format.
  •  Above all addresses can be converted to hexadecimal format using hex function.
  • While hex() returns the hexadecimal value so it will print the address.
var1 = 2.60
print(hex(id(var1))) # print the address of var1 in hexadecimal format
var2 = 3.90
print(hex(id(var2))) #print the address of var2 in hexadecimal format
print(hex(id(str1))) #print the address of str1 in hexadecimal format

Hence you can use id() to find the address of variables in Python.

Also read: Python id() function

One response to “Find the memory Address of a variable in Python”

  1. Dr.Sai B K says:

    I have a list in a variable:
    I want to assign the list A to another variable ‘z’ in a program (not manually)
    what can be the code? Can the id() be used for this task? if yes, how?

Leave a Reply

Your email address will not be published. Required fields are marked *