Concepts / Working with Sequences

Working with Sequences

Indexing lets you read an item from a string; it does not give you permission to assign a new item into that string.

  • Programming

The tempting character change

When you first learn indexing, it is natural to think that reading and changing should work in similar ways. A string is a sequence of characters, so you can read the character at position 0 with greeting[0]. However, Python does not allow you to replace that character directly. Strings are immutable: once a string has been created, its contents cannot be changed.

python

What do you think happens?

What happens when the second line tries to replace the character at index 0?

  • The string becomes 'Jello'.

  • A new string is created automatically.

  • Python raises a TypeError.

Reveal answer
Answer:

Python raises a TypeError.

The assignment tries to change one item inside a string. String contents cannot be modified after creation, so Python rejects the assignment.

What remains after the failed assignment

greetingHelloindex 0 assignmentreplace HgreetingHelloTypeErrorassignment rejectedread index 0no string changeraises
What happens to the original string when code tries to change one of its characters?

The failed assignment does not produce a partly changed string. Python stops the assignment by raising a TypeError. The message str object does not support item assignment identifies the problem precisely: the object is the string, and the item is the individual character at the selected index. This kind of object does not allow a new value to be assigned to one of its items.

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

Reading versus changing items

greetingstring valuegreeting[0]character itemitem assignmentnew characterTypeErrornot supportedreadtry to replacestring rejects change
How does execution flow from indexing a string to the TypeError raised by assigning a new character?
Definition

Immutable means that an object cannot be changed after it has been created. For strings, this means that individual characters cannot be replaced through item assignment.

Key point

Indexing lets you read an item from a string; it does not give you permission to assign a new item into that string.

Building a replacement string

When a string needs to appear different, do not try to modify one of its characters. Instead, create a new string variation. Keep the portions of the original string that you want, add the replacement content, and assign the combined result to a variable. Slicing selects parts of the original string, while concatenation joins string parts together.

greetingHelloslicecharacters to keepnew stringJellonew characterJslicecharacters to keeptake parttake partconcatenateconcatenateconcatenate
How do slices and added characters flow together to produce a new string without changing the original?
python

This expression takes the part before index 0, adds J, and then adds the part beginning at index 1. The result is a new string variation. The original greeting remains unchanged, while new_greeting refers to the constructed variation.

Output
greeting: 'Hello'
new_greeting: 'Jello'

Original value and new variation

greetingHelloitem assignmentTypeErrorslices andcharacterparts to combinenew_greetingJelloattempt to modifyconcatenate
What is the difference between changing an existing string and creating a separate new string?
OperationWhat happensResult
Assign a new character at an indexAttempts to change an existing string itemTypeError
Use slicing and concatenationCombines selected original parts with new contentA new string variation

Two different approaches to getting a changed-looking string

Why immutability helps

Immutability is a feature rather than merely a restriction. Because strings cannot change, Python can safely use them as dictionary keys. If a string used as a key could later be modified, the dictionary could break. Immutability also allows memory optimization when variables refer to the same string value. In addition, a function that receives a string cannot accidentally alter that string and affect other code using it.

  • Strings can safely be used as dictionary keys because their contents do not change.
  • Python can optimize memory when variables refer to the same string value.
  • Passing a string to a function does not allow the function to alter that string for other code.

Mistakes with string changes

  • Common mistake

    Treating a string index like a writable slot

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

    A string is immutable, so it does not support assigning a new value to one of its items.

    Do this instead

    Use slicing and concatenation to construct a new string.

  • Common mistake

    Assuming that a failed assignment changes part of the string

    What it looks like

    Expecting 'Hello' to become 'Jello' after the TypeError

    Why it fails

    Python rejects the assignment and raises a TypeError rather than partially changing the string.

    Do this instead

    Treat the original string as unchanged and build a separate variation.

  • Common mistake

    Confusing reassignment with mutation

    What it looks like

    Assigning a newly concatenated result to the same variable name

    Why it fails

    The name can be assigned a new string, but the previously created string itself was not modified.

    Do this instead

    Understand the operation as creating a new string and storing it under a variable name.

Practice the distinction

EASY

Suppose greeting contains the string Hello. Describe what happens when a program tries to assign J to index 0. Then describe how slicing and concatenation can produce Jello while leaving the original string unchanged.

Hints
  • Identify whether the operation changes an item inside the existing string or constructs a new value.
  • The direct index assignment raises a TypeError.
  • The replacement approach keeps selected parts of the original and concatenates them with the new character.
Worked example

Choosing the valid approach

A learner wants to change the first character of Hello to J.

  1. 1
    Identify the invalid operation

    Assigning a value to the first character attempts to modify a string item directly, so Python raises a TypeError.

  2. 2
    Keep the original parts

    Use slicing to select the portions of the original string that should remain.

  3. 3
    Add the replacement

    Concatenate the new character between the selected portions to construct a new string variation.

Result

The original string remains unchanged, and a new string with the desired variation is created.

The sequence rule to remember

  1. 1
    Strings are immutable, so their characters cannot be changed after creation.
  2. 2
    Attempting character assignment produces a TypeError because strings do not support item assignment.
  3. 3
    Slicing and concatenation create a new string variation from selected original parts and new content.
  4. 4
    Creating a new string is different from modifying the existing string, even when the result is assigned to the same variable name.
  5. 5
    Immutability supports safe dictionary keys, memory optimization, and protection against accidental changes.

Key Takeaways

  • A string is an immutable sequence of characters.
  • Reading a character by index is allowed, but assigning a new character by index raises a TypeError.
  • Use slicing and concatenation to build a new string variation.
  • The original string is not modified, even when the new result is stored under the same variable name.
  • Immutability helps Python use strings safely as dictionary keys and prevents accidental changes.

Related concepts

More concepts starting with W