Last updated: Apr 8, 2024
Reading timeยท8 min
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.
Here is an example of how the error occurs.
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.
One way to solve the error is to use the str.replace()
method to get a new,
updated string.
my_str = 'apple, banana, apple' new_str = my_str.replace('apple', 'melon') print(new_str) # ๐๏ธ "melon, banana, melon"
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:
Name | Description |
---|---|
old | The substring we want to replace in the string |
new | The replacement for each occurrence of old |
count | Only the first count occurrences are replaced (optional) |
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
.
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.
One way to replace a character at a specific index in a string is to:
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'
We passed the string to the list() class to get a list containing the string's characters.
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.
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.
If you need to reassign a string variable by adding characters to it, use the
+=
operator.
my_str = 'bobby' my_str += 'hadz' print(my_str) # ๐๏ธ bobbyhadz
The +=
operator is a shorthand for my_str = my_str + 'new'
.
The code sample achieves the same result as using the longer form syntax.
my_str = 'bobby' my_str = my_str + 'hadz' print(my_str) # ๐๏ธ bobbyhadz
Here is an example that replaces an underscore at a specific index with a space.
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"
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
.
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.
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.
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.
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.
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.
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.
Here is an example of how the error occurs.
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.
If you meant to declare another integer, declare a separate variable with a different name.
my_int = 123 print(my_int) # ๐๏ธ 123 my_other_int = 9 print(my_other_int) # ๐๏ธ 9
Primitives like integers, floats and strings are immutable in Python.
If you meant to change an integer value in a list, use square brackets.
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
.
append()
method to add an item to the end of the list or the insert()
method to add an item at a specific index.If you have two-dimensional lists, you have to access the list item at the correct index when updating it.
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.
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.
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.
If you need to get a new list by running a computation on each integer value of the original list, use a list comprehension.
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.
If you aren't sure what type a variable stores, use the built-in type()
class.
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.
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.
Here is an example of how the error occurs.
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.
If you mean to declare another floating-point number, simply declare a separate variable with a different name.
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
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.
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
.
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.
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.
If you have a two-dimensional array, access the array element at the correct index when updating it.
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
.
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.
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.