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

Can some one explain what it means that Strings are immutable?

I understand that it means strings can not be changed but im not sure if im following:

dessert = "Ice Cream" 'Ice Cream' dessert = "Ice Cream and Pie" 'Ice Cream and Pie'

I know im just changing the variable but the concept that strings are immutable is not making sense.

2 Answers

A good way to think of it conceptually is first think of something that is mutable(can be changed). So lets take a list for example. Say you have a list of students.

students = ['Bob', 'Gary', 'Steven']. If you take out one of those students from the list (because its mutable) you still would have a list of students. So the variable would make sense.

Now think of a string. will use the variable name fruit.

fruit = "apple"

This is immutable because if you take out the a (index[0] of the string) you now have 'pple' which changes the complete value of that variable. At least thats how I like to think about it. Hope it was a little helpful. I supplied a link to a free python book I use that I found helpful. The link is in regards to the strings chapter.

https://automatetheboringstuff.com/chapter6/

Steven Parker
Steven Parker
243,318 Points

In your example you assign the variable "dessert" to a string. Then you re-assign that same variable to another string.

The important fact is that you are not changing the string itself, just changing the variable to refer to a different one.

Perhaps this example will better illustrate immutability:

x = "test"
print(x[2])  # this will show the letter 's'
x[2] = "n"   # this will cause an error because you cannot change the string itself