Variables in Python

 So, the variables in Python are very different than those of other languages like C/C++, the variables in Python are references to some values stored in the memory under the hood. When we do a=12, or something like that then actually  the variable a gets the reference of the memory where the value of  that variable is stored in the memory. In a language like C++, a variable is just a named memory location and if we want the references of some memory locations then we have to use pointers in those languages but it's not the case in Python.

The biggest question that comes in mind is that what happens when we pass a variable in a function and change it, because the variable is a reference then changes should be made in the memory location of that particular variable where it is referencing to.

In contrast to the intuition, on changing the value of a variable inside a function a new reference is given to the variable. The case of lists is quite interesting because in case of lists, +=  and =+ behave differently.  Basically when we have a list ls and we change it using the format ls+=[1,2,3] then the change is made in the original location of the list and no new reference is given to the variable ls but for the case of ls=ls+[1,2,3]  a new reference is given to the variable ls like in the case of int, char, str or floats.

A very interesting program to understand this concept:-

ls1=[1,2,3,4]
ls2=ls1
print(*ls1,"id-->",id(ls1))
print(*ls2,"id-->",id(ls2))
ls1=ls1+[5,6,7,8]
print("Values after the change in ls1:-".center(40,"#"))
print(*ls1,"id-->",id(ls1))
print(*ls2,"id-->",id(ls2))

So, the thing to focus on the above code is that ls2 was made equal to ls1, means ls2 has the reference of the list ls1 and when we made change in the list ls1 using the format ls1=ls1+[5,6,7,8] then a new reference was given to the variable ls1 and the list ls2 remained unchanged as there was no change made in the previous location of ls1.

You can very easily infer this by seeing the locations of these list variables, the location of the ls1 changes but that of ls2 remains the same which was the previous location of the variable ls1.

But the interesting part is when we do the same thing in a different way as below:-

In the below code the location of both the lists remain the same, and the changes made in ls1 are also reflected in the list ls2.

ls1=[1,2,3,4]
ls2=ls1
print(*ls1,"id-->",id(ls1))
print(*ls2,"id-->",id(ls2))
ls1+=[5,6,7,8]
print("Values after the change in ls1:-".center(40,"#"))
print(*ls1,"id-->",id(ls1))
print(*ls2,"id-->",id(ls2))

Comments

Popular Posts