Basic of Python - Variable and Memory Address
About this Post
In this post I will be demonstrating how python works using example of variables and their memory addresses.
Explanation with Python Code Examples
#create a variable with value 10
var = 10
#id function is used to get the memory address
print(id(var)) #1712357776 - memory address
#assign var_new equals to var
var_new = var
#var_new and var are now attached to same memory address
print(id(var_new))#1712357776 - memory address
#reassign value of var
var = 20
#var gets detached from memory address of 10 and then attached to the memory address of 20 .We can see different memory address now
print(id(var))#1712358096 -memory address
#var_new has old memory address because it is attached to memory address of 10
print(id(var_new))#1712357776 - memory address
print(var) #20
print(var_new) #10
Now rather than reassigning value we will try to update the variable value. For this we can take list / dictionary example.
# taking a list variable
list_var = [1,2,3,4]
print(id(list_var))#2257786114760 -memory address
#assign list_var_new equals to list_var
list_var_new = list_var
#list_var_new and list_var are now attached to same memory address
print(id(list_var_new))#2257786114760 -memory address
#now instead of reassign ,append an element in list_var
list_var.append(5)
#memory address of list_var will remain same as we are not reassigning it . We are adding one more element in it
print(id(list_var))#2257786114760 -memory address
#memory address of list_var_new is same as list_var
print(id(list_var_new))#2257786114760 -memory address
print(list_var) # [1,2,3,4,5]
#as list_var_new is attached to same memory address as that of list_var, value of list_var_new has updated along with list_var
print(list_var_new) # [1,2,3,4,5]
How to create a copy of variable with different memory address.
For this we will use copy module of python
import copy
list_1 = [1,2,3,4]
list_2 = copy.copy(list_1)
print(id(list_1)) #2257786155784 - memory address
print(id(list_2)) #2257786177544 - memory address
list_1.append(5)
print(id(list_1)) #2257786155784 - memory address
print(id(list_2)) #2257786177544 - memory address
print(list_1) # [1,2,3,4,5]
#value if list_2 won't change now as both variable has different memory address
print(list_2) # [1,2,3,4]
Nice u have covered very wode area in a very short note bhaiya... Keep doing👌🤘
ReplyDelete