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

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Immutability Quirks and Oddities in Python

Give Feedback

This is the last lesson of the course and covers quirks and oddities arising when using immutable objects. One of these oddities is a (immutable) tuple containing a (mutable) list. This example is covered in more depth in the video.

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 Sims on July 3, 2019

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

andersstenborgmartin on July 15, 2020

Very clear and concise!

Ghani on Oct. 17, 2020

Very interesting; thank you so much!

Become a Member to join the conversation.