Concepts / Lists and Mutability

Lists and Mutability

Strings are immutable: once created, they cannot be changed. Attempting to assign a new value to a character at a specific index raises a TypeError.

  • 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.

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

What immutable means

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

Changing Hello to Jello

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

Keep the part before the replacement: The portion before index 0 is empty, so there is no earlier text to keep.

Choose the replacement content: Use the new character J.

Keep the remaining portion: Use the part of the original string after its first character, which is ello.

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

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

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

Reassigning the same name

greeting = 'Hello' greeting = greeting[:0] + 'J' + greeting[1:] print(greeting)

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.

executeunsupportedHellogreetingitem assignmentgreeting[0] = 'J'TypeErrorexecution stops
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
containsreplacecontainsreplace attemptlist'H'position 0string'H'position 0'J'position 0TypeErroritem assignment unsupported
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

  • Trying to replace a string character with item assignment.

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

    Fix: Use slicing and concatenation to build a new string.

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

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

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

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

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

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

Key Takeaways

  • 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.