Variable Assignment in Python
There are 2 types of variable in Python - Mutable and Immutable. In this tutorial, we will discuss about different variable assignment, mutable and immutable variable assignment.
Immutable Variable Assignment
What happens when we assign an integer to a variable such as
x = 50. In this case, Python creates an int object with a value of 50 and assigns an object reference with a name x. Now, when we assign x with another value such as 100 then the object actual value i.e. 50 is not changed as int is immutable in Python. Here, Python creates another immutable object with a value 100 and the reference of x changes to 100 and the object with vaue 50 is lost and collected by Python garbage collection.
Now, when we assign another variable y to x like y = x then the object reference of object 100 is assignedd to y too. Now when we assign x to 200 such as
x = 200 then the reference of the object 200 is assigned to x but the reference of object 100 is still asssigned to y and hence no object is garbage collected.
To verify the above concept, let us use inbuilt function
id() which returns a unique identifier for an object.
x = 50 print(id(x)) x = 100 print(id(x)) # reference of x changes y = x # same reference as x print(id(y)) x = 200 print(id(x)) # reference of x changes print(id(y)) # y is still referencing to previous reference of 100Output
140737173842288 140737173843888 140737173843888 140737173847088 140737173843888
Mutable Variable Assignment
As we know list in Python is mutable. Hence, if 2 variables are referencing the same list and if we change the value of the list, still the variable references will not be changed as no new list is created instead the object is modified as list is immutable. The test x is y returns True as both the variable is referencing to same object.
x = [12, 45, 100] y = x print(y) x = 200 print(x) print(y) print(x is y)Output
[12, 45, 100] [12, 200, 100] [12, 200, 100] True
Note: Assigning to new variable does not copy the value instead the reference is only copied.
In this tutorial, we learnt about different variable assignment, mutable and immutable variable assignment.
If You Appreciate This, You Can Consider:
About The Author
I am an energetic professional who enjoys the challenges involved in working with people and resolving real-time problems. Technical expertise in building highly scalable, distributed and self-healing cloud applications. Technical Skills: Java/J2EE, Spring Framework, Hibernate, Angular, Reactive Programming, Microservices, Rest APIs, Kafka, ELK, etc.