Python Variables don't VARY!
We always have told that variable is vary+able because their content can be changed.
Today we are going on a new journey to see what exactly these variables are!
Don't forget to take the id() function with you to manage Variables in the Journey !
Lets Begin ✊✊
a = 10
print(a)a = 11
We can see a got changed to the new value 11 🤔 so is a that variable ?
#print(id(a)) NameError: name 'a' is not definedprint(id(10))a=10
Before assigning int object 10 to a we directly tried both of them in our id() and id knows 10 and printed its address, but when we tried a it just said “I don't know this ”
2 Points to conclude from here
- id() knew 10 as all the numbers are int objects
- = operator assigned the int object 10’s memory address in ‘a’
Now, as we have got the idea using id() let's rewrite the previous code once again
a = 10
print(id(a))a = 11
print(id(a))b = 10
2 Points to note from here:
- There are 2 int objects 10 & 11, which are pointed by b and a respectively.
- After a changed the reference from 10 to 11, 10 object remained in the same address so when b was assigned 10 that same old 10 was assigned to ensure code reusability.
So whenever python finds a =10 it stores 10 an int object into a specific memory location and put a as a pointer towards that location.
Here a is just an identifier or pointer which points toward a memory location where 10 is stored.
Whenever a python object loses the reference it will be removed by the garbage collector internally at the specified time.
All the function names and data type names are stored like built-in variables and we can access their location using id()
for i in int,float,tuple,list,complex,str,print,id,type,True,False, None :print(id(i))OUTPUT94046028248960
We can also use the above built-in variables to assign user defined values but it can hinder our normal execution.
int = 456
float = -87
complex = 76.78
print(int, float, complex)print(int(),float(), complex())
print(print)OUTPUTTypeError: 'int' object is not callable
Hence we saw that the variable concept is made up of variable name, memory location and the stored objects and it doesn’t change by any of our actions except when its mutable. The un-refered memory locations are cleared but only implicitly!
Thats all !
Hope you all liked the journey !
Happy Learning !!