Concepts / Lists and Mutability

Lists and Mutability

Immutability is a feature rather than merely a restriction.

  • Programming

The tempting assignment

When you learn indexing, it is natural to think that reading and changing should work in similar ways. You can read the first character of greeting with greeting[0]. It may therefore seem reasonable to write greeting[0] = 'J' when changing Hello to Jello. Python does not permit this operation because strings are immutable.

What do you think happens?

What happens when Python evaluates greeting[0] = 'J' for the string Hello?

  • The first character changes and the string becomes Jello

  • Python raises a TypeError

  • Python creates a list automatically

  • The assignment changes only the displayed output

Reveal answer
Answer:

Python raises a TypeError.

A string does not support assignment to one of its items. The attempted assignment targets the character at index 0, but string contents cannot be modified in place.

The failed string update

python
Output
TypeError: 'str' object does not support item assignment

The error message identifies the problem precisely. The object is the string value greeting. The item is the individual character at index 0. Python is telling you that a string object does not allow a new value to be assigned to one of its items. The assignment fails at that statement, so the attempted character replacement does not occur.

greetingHelloindex 0Hgreeting[0] = 'J'attempted assignmentTypeErroritem assignment unsupportedcontainstargetsraises
What happens to the string and program state when code tries to replace the character at index 0?

What immutable means

Definition

Immutable means that once a string has been created, its contents cannot be changed. Reading characters from a string is allowed, but assigning a new value to one of those characters is not.

Immutability does not mean that you can never have a different string. It means that the existing string remains unchanged. To produce a variation, take the parts you want to keep, add the replacement content, and create a new string. The result can be stored under a new variable name or assigned back to the same variable name.

Building a replacement

Worked example

Changing Hello to Jello

Create a new string whose first character is J while keeping the rest of Hello.

  1. 1
    Keep the part before the replacement

    The portion before index 0 is empty, so there is no earlier text to keep.

  2. 2
    Choose the replacement content

    Use the new character J.

  3. 3
    Keep the remaining portion

    Use the part of the original string after its first character, which is ello.

  4. 4
    Join the parts

    Concatenate the kept portion, the replacement character, and the remaining portion to produce Jello.

Result

The new string is Jello, while the original string value Hello remains unchanged.

python
Output
Hello
Jello
greetingHellogreeting[:0]empty text'J'new contentnew_greetingJellogreeting[1:]elloslicesliceconcatenateconcatenateconcatenate
How do slicing and concatenation use parts of the original string to produce a separate new string?

Reassigning the same name

Code walkthrough
greeting = 'Hello'
greeting = greeting[:0] + 'J' + greeting[1:]
print(greeting)
  1. 1
    The first line creates the original string value Hello.
  2. 2
    The second line reads parts of the original and combines them with J. The resulting string is Jello, and the variable name is assigned that result.
  3. 3
    The final line displays the new value associated with greeting.
  • The variable greeting is first associated with Hello.
  • Slicing and concatenation produce a new string variation.
  • The variable name greeting is then associated with the new string value.
  • The original string was not modified in place.
Output
Jello

Using the same variable name can make the operation look like a mutation, but the mechanism is different. Python first builds a new string from slices and concatenation. Then the name can be assigned to that new result. The earlier string itself remains immutable.

Hellogreetingitem assignmentgreeting[0] = 'J'TypeErrorexecution stopsexecuteunsupported
What operation triggers the TypeError, and where does execution stop?

Strings beside lists

OperationStringList
Read an item at a positionAllowedAllowed
Replace an item at a positionNot allowed; raises TypeErrorAllowed in the mutable-list comparison
Produce a changed sequenceCreate a new string with slicing and concatenationReplace the item in the list

The important distinction is that strings are immutable, while lists are used as the mutable comparison in this topic.

list'H'position 0string'H'position 0'J'position 0TypeErroritem assignment unsupportedcontainsreplacecontainsreplace attempt
What changes inside a list versus a string when an element at a position is replaced?

Why immutability helps

Immutability is a feature rather than merely a restriction. Python can safely use strings as dictionary keys because their contents cannot change after they are used as keys. Immutability can also allow memory optimization when two variables reference the same string value. In addition, a function that receives a string cannot accidentally alter that string and affect code elsewhere in the program.

Common assignment mistakes

  • Common mistake

    Trying to replace a string character with item assignment.

    What it looks like
    greeting[0] = 'J'
    Why it fails

    Strings are immutable, so a string does not support assignment to one of its items.

    Do this instead

    Use slicing and concatenation to build a new string.

  • Common mistake

    Assuming that reading an indexed character means the character can also be changed.

    What it looks like

    Reading greeting[0] works, so changing greeting[0] should work too.

    Why it fails

    Reading an item and assigning a new item are different operations. Python allows the read but rejects the string item assignment.

    Do this instead

    Treat indexed string access as a way to inspect a character, not as permission to replace it.

  • Common mistake

    Thinking that assigning the new result back to the same variable mutates the original string.

    What it looks like
    greeting = greeting[:0] + 'J' + greeting[1:]
    Why it fails

    The expression creates a new string variation before the variable name is assigned that result.

    Do this instead

    Recognize the operation as creating a new string and then assigning the variable name to it.

Practice the distinction

EASY

For the code below, predict which line raises an error. Then rewrite the code so that the final value displayed is Jello without using item assignment.

greeting = 'Hello'
greeting[0] = 'J'
print(greeting)
Hints
  • The error is raised when the code attempts to assign a value to one character.
  • Keep the part after the first character and concatenate it with J.
  • The corrected version must create a new string variation.
python
Output
Jello

Key takeaways

  1. 1
    Strings are immutable: once created, their contents cannot be changed.
  2. 2
    Assigning a new value to a string character raises TypeError with the message 'str' object does not support item assignment.
  3. 3
    Slicing and concatenation create a new string variation from selected parts of the original and new content.
  4. 4
    Assigning the new result back to the same variable name does not change the original string in place.
  5. 5
    Immutability supports safe dictionary keys, memory optimization, and protection against accidental changes.

At a glance

  • Strings cannot be modified after creation.
  • String item assignment raises a TypeError because strings do not support changing individual characters.
  • Use slicing and concatenation to create a new string variation.
  • Reassigning a variable to the new string is different from mutating the original string.
  • String immutability provides useful safety and implementation benefits.

More concepts starting with L