Start learning free

LESSON 62 OF 673 · STRINGS I

String Immutability in Python

Lesson

In Python, strings are immutable, which means that they cannot be altered once created.

For example, the following code:

message = "Jello world"

message[0] = 'H'

would produce TypeError: 'str' object does not support item assignment.


Variable can still be changed:

Note that this does not mean that message cannot be changed, just that the individual characters of a string literal cannot be changed.

"Jello world" is a string literal that Python stores in memory, while message is a variable that refers to that string literal.

When we do message[0] = 'H', we are trying to alter the string literal "Jello world", which is not allowed.

But like any other variable, message can be changed by reassigning it with a new string, like this:

message = "Jello world"

message = "Hello world"

print(message)

This code would output:

Hello world

Instead of trying to alter the first string, this code now creates a new one ("Hello world"), stores it in memory and tells message to refer to this new string.


Assignment
Follow the Coding Tutorial and let's practice with string immutability!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check