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.

Unlock This Lesson

Immutability Quirks and Oddities in Python

Give Feedback

Comments & Discussion

chmayurnath on April 18, 2019

Hi,

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

eg String str=”abc” str=”xyz”

if we print str it would be xyz. why str is getting modified if we reassign a complete value.

Thanks

Hi, 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

Thanks Understood.

Abby Jones on June 28, 2019

This really is quirky but I dig it. Being able to access a mutable object within an immutable object.

Tonya S on July 3, 2019

Wow! This video series cleared up so much confusion for me regarding immutable objects! Thank you Dan!

Become a Member to join the conversation.