Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Tim Mossholder
The Python "TypeError: 'float' object does not support item assignment" occurs when we try to assign a value to a 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.
my_float = 1.1 # ⛔️ TypeError: 'float' object does not support item assignment my_float[0] = 5
We tried to access the float at index 0
and change the digit which caused the
error.
If you mean to declare another floating-point number, simply declare a separate variable with a different name.
my_float = 1.1 my_other_float = 2.2
Primitives like floats, integers and strings are immutable in Python, so chances are you meant to change a float value in a list.
my_list = [1.1, 2.2] my_list[0] = 9.9 print(my_list) # 👉️ [9.9, 2.2] my_list.append(3.3) print(my_list) # 👉️ [9.9, 2.2, 3.3] my_list.insert(0, 10.1) print(my_list) # 👉️ [10.1, 9.9, 2.2, 3.3]
We changed 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.1], [2.2], [3.3]] my_list[0][0] = 9.9 print(my_list)
We accessed the first nested list (index 0
) and then updated the value of the
first item in the nested list.
If you need to get a new list by running a computation on each float value of the original list, use a list comprehension.
my_list = [1.1, 2.2, 3.3] my_new_list = [x + 1.5 for x in my_list] print(my_new_list) # 👉️ [2.6, 3.7, 4.8]
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.
my_float = 3.3 print(type(my_float)) # 👉️ <class 'float'> print(isinstance(my_float, float)) # 👉️ 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.