TypeError: 'str' object does not support item assignment

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
8 min

banner

# Table of Contents

  1. TypeError: 'str' object does not support item assignment
  2. TypeError: 'int' object does not support item assignment
  3. 'numpy.float64' object does not support item assignment

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

The Python "TypeError: 'str' object does not support item assignment" occurs when we try to modify a character in a string.

Strings are immutable in Python, so we have to convert the string to a list, replace the list item and join the list elements into a string.

typeerror str object does not support item assignment

Here is an example of how the error occurs.

main.py
my_str = 'abc' # โ›”๏ธ TypeError: 'str' object does not support item assignment my_str[0] = 'z'

We tried to change a specific character of a string which caused the error.

Strings are immutable, so updating the string in place is not an option.

Instead, we have to create a new, updated string.

# Using str.replace() to get a new, updated string

One way to solve the error is to use the str.replace() method to get a new, updated string.

main.py
my_str = 'apple, banana, apple' new_str = my_str.replace('apple', 'melon') print(new_str) # ๐Ÿ‘‰๏ธ "melon, banana, melon"

using str replace to get new updated string

The str.replace() method returns a copy of the string with all occurrences of a substring replaced by the provided replacement.

The method takes the following parameters:

NameDescription
oldThe substring we want to replace in the string
newThe replacement for each occurrence of old
countOnly the first count occurrences are replaced (optional)
Note that the method doesn't change the original string. Strings are immutable in Python.

By default, the str.replace() method replaces all occurrences of the substring in the string.

If you only need to replace the first occurrence, set the count argument to 1.

main.py
my_str = 'apple, banana, apple' new_str = my_str.replace('apple', 'melon', 1) print(new_str) # ๐Ÿ‘‰๏ธ "melon, banana, apple"

Setting the count argument to 1 means that only the first occurrence of the substring is replaced.

# Replacing a character with a conversion to list

One way to replace a character at a specific index in a string is to:

  1. Convert the string to a list.
  2. Update the list item at the specified index.
  3. Join the list items into a string.
main.py
my_str = 'abc' my_list = list(my_str) print(my_list) # ๐Ÿ‘‰๏ธ ['a', 'b', 'c'] my_list[0] = 'z' new_str = ''.join(my_list) print(new_str) # ๐Ÿ‘‰๏ธ 'zbc'

replace character with conversion to list

We passed the string to the list() class to get a list containing the string's characters.

Lists are mutable, so we are able to change the list item at the specified index.

The last step is to join the list items into a string with an empty string separator.

The str.join() method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(a_string) - 1.

If you have to do this often, define a reusable function.

main.py
def update_str(string, index, new_char): a_list = list(string) a_list[index] = new_char return ''.join(a_list) new_str = update_str('abc', 0, 'Z') print(new_str) # ๐Ÿ‘‰๏ธ Zbc

The update_str function takes a string, index and new characters as parameters and returns a new string with the character at the specified index updated.

An alternative approach is to use string slicing.

# Reassigning a string variable

If you need to reassign a string variable by adding characters to it, use the += operator.

main.py
my_str = 'bobby' my_str += 'hadz' print(my_str) # ๐Ÿ‘‰๏ธ bobbyhadz

reassigning string variable

The += operator is a shorthand for my_str = my_str + 'new'.

The code sample achieves the same result as using the longer form syntax.

main.py
my_str = 'bobby' my_str = my_str + 'hadz' print(my_str) # ๐Ÿ‘‰๏ธ bobbyhadz

# Using string slicing to get a new, updated string

Here is an example that replaces an underscore at a specific index with a space.

main.py
my_str = 'hello_world' idx = my_str.index('_') print(idx) # ๐Ÿ‘‰๏ธ 5 new_str = my_str[0:idx] + ' ' + my_str[idx+1:] print(new_str) # ๐Ÿ‘‰๏ธ "hello world"

using string slicing to get new updated string

The first piece of the string we need is up to, but not including the character we want to replace.

The syntax for string slicing is a_string[start:stop:step].

The start index is inclusive, whereas the stop index is exclusive (up to, but not including).

The slice my_str[0:idx] starts at index 0 and goes up to, but not including idx.

main.py
my_str = 'hello_world' print(my_str[0:5]) # ๐Ÿ‘‰๏ธ "hello"

The next step is to use the addition + operator to add the replacement string (in our case - a space).

The last step is to concatenate the rest of the string.

Notice that we start the slice at index + 1 because we want to omit the character we are replacing.

main.py
my_str = 'hello_world' print(my_str[5 + 1:]) # ๐Ÿ‘‰๏ธ "world"

We don't specify an end index after the colon, therefore the slice goes to the end of the string.

We simply construct a new string excluding the character at the specified index and providing a replacement string.

main.py
my_str = 'hello_world' idx = my_str.index('_') print(idx) # ๐Ÿ‘‰๏ธ 5 new_str = my_str[0:idx] + ' ' + my_str[idx+1:] print(new_str) # "hello world"

If you have to do this often define a reusable function.

main.py
def get_updated_str(string, index, new_char): return string[:index] + new_char + string[index+1:] new_str = get_updated_str('abcd', 0, 'Z') print(new_str) # ๐Ÿ‘‰๏ธ Zbcd

The function takes a string, index and a replacement character as parameters and returns a new string with the character at the specified index replaced.

If you need to update multiple characters in the function, use the length of the replacement string when slicing.

main.py
def get_updated_str(string, index, new_chars): return string[:index] + new_chars + string[index+len(new_chars):] new_str = get_updated_str('abcd', 0, 'ZX') print(new_str) # ๐Ÿ‘‰๏ธ ZXcd new_str = get_updated_str('abcd', 0, 'ZXY') print(new_str) # ๐Ÿ‘‰๏ธ ZXYd new_str = get_updated_str('abcd', 0, '_') print(new_str) # ๐Ÿ‘‰๏ธ _bcd

The function takes one or more characters and uses the length of the replacement string to determine the start index for the second slice.

If the user passes a replacement string that contains 2 characters, then we omit 2 characters from the original string.

# Table of Contents

  1. TypeError: 'int' object does not support item assignment
  2. 'numpy.float64' object does not support item assignment

# TypeError: 'int' object does not support item assignment

The Python "TypeError: 'int' object does not support item assignment" occurs when we try to assign a value to an integer using square brackets.

To solve the error, correct the assignment or the accessor, as we can't mutate an integer value.

typeerror int object does not support item assignment

Here is an example of how the error occurs.

main.py
my_int = 123 # โ›”๏ธ TypeError: 'int' object does not support item assignment my_int[0] = 9

We tried to change the digit at index 0 of an integer which caused the error.

# Declaring a separate variable with a different name

If you meant to declare another integer, declare a separate variable with a different name.

main.py
my_int = 123 print(my_int) # ๐Ÿ‘‰๏ธ 123 my_other_int = 9 print(my_other_int) # ๐Ÿ‘‰๏ธ 9

# Changing an integer value in a list

Primitives like integers, floats and strings are immutable in Python.

If you meant to change an integer value in a list, use square brackets.

main.py
my_list = [1, 2, 3] my_list[0] = 9 print(my_list) # [9, 2, 3] my_list.append(4) print(my_list) # [9, 2, 3, 4] my_list.insert(0, 10) print(my_list) # [10, 9, 2, 3, 4]

Python indexes are zero-based, so the first item in a list has an index of 0, and the last item has an index of -1 or len(a_list) - 1.

We used square brackets to change the value of the list element at index 0.

You can use the append() method to add an item to the end of the list or the insert() method to add an item at a specific index.

# Updating a value in a two-dimensional list

If you have two-dimensional lists, you have to access the list item at the correct index when updating it.

main.py
my_list = [[1], [2], [3]] my_list[0][0] = 9 print(my_list) # ๐Ÿ‘‰๏ธ [[9], [2], [3]]

We accessed the first nested list (index 0) and then updated the value of the first item in the nested list.

# Reassigning a list to an integer by mistake

Make sure you haven't declared a variable with the same name multiple times and you aren't reassigning a list to an integer somewhere by mistake.

main.py
my_list = [1, 2, 3] my_list = 100 # โ›”๏ธ TypeError: 'int' object does not support item assignment my_list[0] = 'abc'

We initially declared the variable and set it to a list, however, it later got set to an integer.

Trying to assign a value to an integer causes the error.

To solve the error, track down where the variable got assigned an integer and correct the assignment.

# Getting a new list by running a computation

If you need to get a new list by running a computation on each integer value of the original list, use a list comprehension.

main.py
my_list = [1, 2, 3] my_new_list = [x + 10 for x in my_list] print(my_new_list) # ๐Ÿ‘‰๏ธ [11, 12, 13]

The Python "TypeError: 'int' object does not support item assignment" is caused when we try to mutate the value of an int.

# Checking what type a variable stores

If you aren't sure what type a variable stores, use the built-in type() class.

main.py
my_int = 123 print(type(my_int)) # ๐Ÿ‘‰๏ธ <class 'int'> print(isinstance(my_int, int)) # ๐Ÿ‘‰๏ธ True

The type class returns the type of an object.

The isinstance() function returns True if the passed-in object is an instance or a subclass of the passed-in class.

# 'numpy.float64' object does not support item assignment

The Python "TypeError: 'numpy.float64' object does not support item assignment" occurs when we try to assign a value to a NumPy float using square brackets.

To solve the error, correct the assignment or the accessor, as we can't mutate a floating-point number.

typeerror numpy float64 object does not support item assignment

Here is an example of how the error occurs.

main.py
import numpy as np my_float = np.float64(1.1) # โ›”๏ธ TypeError: 'numpy.float64' object does not support item assignment my_float[0] = 9

We tried to change the digit at index 0 of a NumPy float.

# Declaring multiple floating-point numbers

If you mean to declare another floating-point number, simply declare a separate variable with a different name.

main.py
import numpy as np my_float = np.float64(1.1) print(my_float) # ๐Ÿ‘‰๏ธ 1.1 my_other_float = np.float64(2.2) print(my_other_float) # ๐Ÿ‘‰๏ธ 2.2

# Floating-point numbers are immutable

Primitives such as floats, integers and strings are immutable in Python.

If you need to update a value in an array of floating-point numbers, use square brackets.

main.py
my_arr = np.array([1.1, 2.2, 3.3], dtype=np.float64) my_arr[0] = 9.9 print(my_arr) # ๐Ÿ‘‰๏ธ [9.9 2.2 3.3]

We changed the value of the array element at index 0.

# Reassigning a variable to a NumPy float by mistake

Make sure you haven't declared a variable with the same name multiple times and you aren't reassigning a list to a float somewhere by mistake.

main.py
import numpy as np my_arr = np.array([1.1, 2.2, 3.3], dtype=np.float64) my_arr = np.float64(1.2) # โ›”๏ธ TypeError: 'numpy.float64' object does not support item assignment my_arr[0] = np.float64(5.5)

We initially set the variable to a NumPy array but later reassigned it to a floating-point number.

Trying to update a digit in a float causes the error.

# When working with two-dimensional arrays

If you have a two-dimensional array, access the array element at the correct index when updating it.

main.py
my_arr = np.array([[1.1], [2.2], [3.3]], dtype=np.float64) my_arr[0][0] = 9.9 # [[9.9] # [2.2] # [3.3]] print(my_arr)

We accessed the first nested array (index 0) and then updated the value of the first item in the nested array.

Python indexes are zero-based, so the first item in a list has an index of 0, and the last item has an index of -1 or len(a_list) - 1.

# Checking what type a variable stores

The Python "TypeError: 'float' object does not support item assignment" is caused when we try to mutate the value of a float.

If you aren't sure what type a variable stores, use the built-in type() class.

main.py
import numpy as np my_float = np.float64(1.1) print(type(my_float)) # ๐Ÿ‘‰๏ธ <class 'numpy.float64'> print(isinstance(my_float, np.float64)) # ๐Ÿ‘‰๏ธ True

The type class returns the type of an object.

The isinstance() function returns True if the passed-in object is an instance or a subclass of the passed-in class.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev