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

omri lahav
omri lahav
434 Points

why I always hear strings are immutable

what does the mean of strings are immutable, if i can change the string by adding something else to it if i use it again?

for ex.

first_name = "omri"

first_name = first_name + "lahav"

omri lahav

i just changed the string so what so immutable here?

3 Answers

Steven Parker
Steven Parker
231,269 Points

This code isn't actually changing the original string. It's building a new string by copying the original one along with the additional characters, and then reassigning the same variable with the new string.

You can demonstrate the immutability of strings by trying to change just one character inside one, for example:

first_name = "omri"
print(first_name[1])    # this will show "m"
first_name[1] = "x"     # but this will fail
omri lahav
omri lahav
434 Points

ho ok thank you very much now i get it :)

Michael Jacoby
seal-mask
.a{fill-rule:evenodd;}techdegree
Michael Jacoby
Full Stack JavaScript Techdegree Student 3,793 Points

""" Following up on this - maybe I just don't understand the concept - but I am on the functions portion of Python basics. The instructor says strings are immutable. That means unable to be changed.
"""

praise = "You are doing great"

The instructor changed it by using the upper function:

praise = praise.upper()

I did the following:

praise = "You are doing great"
praise = "YOU ARE DOING GREAT"
print(praise)

""" Printing doesn't print the original variable stored, it prints what I changed it to, so isn't that the exact opposite of what immutable is supposed to be?

I would expect:

a) either the original variable would print as it is "You are doing great"

or

b) I'd receive some sort of error (unable to update the original variable). """

Steven Parker
Steven Parker
231,269 Points

This is another example of what omri was doing. The string isn't being changed, just replaced with a new one. The variable "praise" is not the actual string, it is just a reference to the string itself.

Try the example I gave to omri to see what happens when you try to change an immutable string.