Python Variables don't VARY!

Abin Isaac
2 min readSep 28, 2021

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
print(a)
OUTPUT10
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
print(id(a))
OUTPUT94581960420128
94581960420128

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

  1. id() knew 10 as all the numbers are int objects
  2. = 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(a)
print(id(a))
a = 11
print(a)
print(id(a))
b = 10
print(b)
print(id(b))
OUTPUT10
94581960420128
11
94581960420160
10
94581960420128

2 Points to note from here:

  1. There are 2 int objects 10 & 11, which are pointed by b and a respectively.
  2. 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.

Built-in Variables

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 
94046028234464
94046028277216
94046028244384
94046028811776
94046028307424
140465722602752
140465722601712
94046028291392
94046028194048
94046028194080
94046028262848

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=97
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 !!

--

--