Join us and get access to hundreds of tutorials and a community of expert Pythonistas.
Unlock This Lesson
This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.
Course: Immutability in Python
chmayurnath on April 18, 2019
I have a doubt on immutability, might be basic, but please clarify .
if I re assign a value to string or tuple variable, it does get changed, Please let me know why
if we print str it would be xyz. why str is getting modified if we reassign a complete value.
RD on April 19, 2019
To answer your question lets first understand what happens when you create a string variable:
str_var = ‘abc’
Python creates an object ‘abc’ in memory, lets say at location 1000 and assigns this object’s reference to str_var variable (= sign)
Now in the next line of your code when you write:
str_var = ‘xyz’
Python creates a new object ‘xyz’, lets say at location 2000 and then assigns it to the str_var.
So we didnt change the ‘abc’ string object. We changed which object the variable str_var is referencing.
Additionally, If you are wondering what happened to the object ‘abc’ , it will be mopped up by garbage collection unless any other variable is referencing it.
chmayurnath on April 24, 2019
Become a Member to join the conversation.