TypePython Error

TypeError

TypeError: 'str' object does not support item assignment

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    name[0] = "H"
TypeError: 'str' object does not support item assignment

What causes this error

An attempt was made to modify a character in a string using index assignment (e.g., s[0] = 'X'). Python strings are immutable and cannot be modified in place.

How to fix it

Create a new string with the desired changes. Use slicing: `s[:i] + new_char + s[i+1:]`. Use `.replace()` for simple substitutions. Convert to list, modify, and join back. Use bytearray for mutable byte sequences.

Code that causes this error

Broken
name = "hello"
name[0] = "H"

Fixed code

Fixed
name = "hello"
name = "H" + name[1:]
# or: name = name.replace("h", "H", 1)

About TypeError

This TypeError is raised when you try to modify a character in a string using index assignment. Strings in Python are immutable — once created, their contents cannot be changed. This is a fundamental design decision in Python: strings, tuples, bytes, and frozensets are all immutable.

The immutability enables strings to be hashable (usable as dict keys and set members) and allows Python to optimize memory by reusing identical string objects. To modify a string, you must create a new string. Common approaches include using string slicing and concatenation, converting to a list of characters and back, using `.replace()` for simple substitutions, or using `bytearray` for mutable byte sequences.

For heavy string manipulation, the `io.StringIO` class provides efficient append operations.

Common scenarios

1

Performing operations between incompatible types like strings and integers

2

Calling methods that return None and chaining operations on the result

3

Passing the wrong number or type of arguments to a function

4

Using bracket notation on objects that do not support indexing

Related errors