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 print(id(var1)) var2 = 12 print(id(var2))
Output:
2037008656
2037008688
- 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))
Output:
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 str1="Hello" print(hex(id(str1))) #print the address of str1 in hexadecimal format
Output: '0x353a208' '0x3500588' '0x352f180'
Hence you can use id() to find the address of variables in Python.
Also read: Python id() function
I have a list in a variable:
A=[25,34,-12]
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?