Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics Types and Branching Strings

What do you mean by "immutable"?

In this python lesson instructor said something about that variables are immutable after they are created. I got the concept but I am still not understanding. Can you give me an example? As a C# and JS programmer, variables can be changed when they are created, example:

 var b= "first text";
 var b= "I have changed or overwritten variable text";

Or Did I misunderstood the concept about "Immutable"? Well I have never heard of it.

1 Answer

As you have probably gathered, to say a variable is immutable means that it cannot be changed. However, it can be more complicated that it may sound at first. For example, a string is immutable in python. However, you can still change what a variable points to. So:

a = "hello"
a = "goodbye"

This is valid, because a is pointing to a new string. The old string did not change, it might even still exist in memory (perhaps another variable is pointing to it). It didn't change. But the variable "a" can still point to a new string. Or for a slightly more complex example:

a = a + " to you"

In this case we are "adding" the strings together. But again, the original strings didn't change, python simply created a new string, and the variable is now referring to this new string

Having said all of this, it's probably worth realizing that you can mostly ignore these issues when you are first starting to learn python. As you get further along, it will become more important, because it can explain why certain tasks are not allowed, or take a very long time. But if you are having difficulty with the concept right now, you might simply want to note that some things are immutable, and that can have certain effects, which are worth noting as they come up. Over time, it will start to make more sense.

Sorry if this isn't as clear as it should be.