TypeError: 'float' object does not support item assignment

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

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

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.

typeerror float object does not support item assignment

Here is an example of how the error occurs.

main.py
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.

main.py
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.

main.py
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.

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.

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.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.

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.

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

main.py
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.

main.py
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.

Use the search field on my Home Page to filter through my more than 1,000 articles.