Last updated: Apr 10, 2024
Reading time·5 min
The Python "TypeError: 'float' object is not subscriptable" occurs when we try to use square brackets to access a float at a specific index.
To solve the error, convert the float to a string before accessing it at an
index, e.g. str(float)[0]
.
Here are 2 examples of how the error occurs.
my_float = 3.123456 # ⛔️ TypeError: 'float' object is not subscriptable result = my_float[0] # -------------------------- list_of_floats = [1.1, 2.2, 3.3, 4.4] # ⛔️ TypeError: 'float' object is not subscriptable list_of_floats[0][1][2] = 5.5
We declared a variable that stores a float and tried to access it at a specific index.
Floating-point numbers are not subscriptable (cannot be accessed at an index).
To solve the error, use the str() class to convert the float to a string or correct the assignment of the variable.
my_float = 3.123456 result = str(my_float) print(result[0]) # 👉️ 3 print(result[2]) # 👉️ 1 print(result[:3]) # 👉️ 3.1
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
.
String objects are subscriptable
, so converting the float to a string solves
the error.
You can use square brackets if you need to access:
If you assigned a float to a variable somewhere in your code by mistake, you have to correct the assignment to a string, list, tuple or dictionary to be able to use square brackets.
my_list = 3.123456 # ⛔️ TypeError: 'float' object is not subscriptable print(my_list[0])
The my_list
variable got assigned a float, so trying to access the float at an
index raised the error.
In this case, you have to track down where the variable got assigned a float and correct the assignment.
The error also commonly occurs when working with lists that contain floating-point numbers.
list_of_floats = [1.1, 2.2, 3.3, 4.4] # ⛔️ TypeError: 'float' object is not subscriptable print(list_of_floats[0][0]) # ----------------------------------- # # ⛔️ TypeError: 'float' object is not subscriptable result[0][1][2] = 5.5
The syntax list[0][0]
tries to access the first digit of the first float in
the list.
If you need to access a specific digit of a list element, convert the element to a string.
list_of_floats = [1.1, 2.2, 3.3, 4.4] first_element = str(list_of_floats[0]) print(first_element) # 👉️ '1.1' print(first_element[0]) # 👉️ '1'
We used the str()
class to convert the float to a string before accessing the
first character (index 0
).
If you need to replace multiple values in a list, use list slicing.
list_of_floats = [1.1, 2.2, 3.3, 4.4] list_of_floats[:3] = [9.9]*3 print(list_of_floats) # 👉️ [9.9, 9.9, 9.9, 4.4]
When the
multiplication *
operator
is used with a list and an integer, a new list containing the items of the
original list repeated N times is returned.
print(['a', 'b'] * 2) # 👉️ ['a', 'b', 'a', 'b'] print(['a'] * 2) # 👉️ ['a', 'a']
Make sure to multiply the list containing the replacement value exactly as many times as there are items in the list slice on the left.
The syntax for list slicing is my_list[start:stop:step]
.
The start
index is inclusive and the stop
index is exclusive (up to, but not
including).
start
index is omitted, it is considered to be 0
, if the stop
index is omitted, the slice goes to the end of the list.The slice list[:3]
selects the first 3 elements of the list (indices 0
, 1
and 2
).
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(my_list) - 1
.
Here is another example of replacing multiple values in the middle of a list.
list_of_floats = [1.1, 2.2, 3.3, 4.4] list_of_floats[1:3] = [9.9]*2 print(list_of_floats) # 👉️ [1.1, 9.9, 9.9, 4.4]
The slice list[1:3]
starts at index 1
and goes up to, but not including
index 3
.
You can also update each value in the list using a separate statement.
list_of_floats = [1.1, 2.2, 3.3, 4.4] list_of_floats[1] = 9.9 list_of_floats[2] = 9.9 print(list_of_floats) # 👉️ [1.1, 9.9, 9.9, 4.4]
The code sample updates the second and third list elements.
You can also use a formatted string literal to convert a float to a string to be able to access it at an index.
my_float = 3.123456 my_str = f'{my_float}' print(my_str) # 👉️ '3.123456' print(my_str[0]) # 👉️ '3' # -------------------------------- # ✅ Round a float to N decimal places my_str = f'{my_float:.2f}' print(my_str) # 👉️ '3.12'
Formatted string literals (f-strings) let us include expressions inside of a
string by prefixing the string with f
.
var1 = 'bobby' var2 = 'hadz' result = f'{var1}{var2}' print(result) # 👉️ bobbyhadz
Make sure to wrap expressions in curly braces - {expression}
.
my_float = 3.123456 my_str = f'{my_float:.1f}' print(my_str) # 👉️ '3.1' my_str = f'{my_float:.2f}' print(my_str) # 👉️ '3.12' my_str = f'{my_float:.3f}' print(my_str) # 👉️ '3.123'
The f
character between the curly braces stands for fixed-point notation.
The character formats the number as a decimal number with the specified number of digits following the decimal point.
If you are taking a
floating-point number from user input, note that the
input()
function always returns a string.
Here are 2 examples of how to take a floating-point number from user input.
# ✅ Take user input float value user_input = float(input('Enter a float: ')) print(user_input) # ------------------------------------------------ # ✅ Take user input float value with validation try: user_input = float(input('Enter a float: ')) print(user_input) except ValueError: print('Enter a valid float')
If you are unsure where a variable got assigned a floating-point number, it
could be due to using the division /
operator.
Division /
of integers yields a float, while
floor division //
of integers results
in an integer.
The result of using the floor division operator is that of a mathematical
division with the floor()
function applied to the result.
my_num = 50 print(my_num / 5) # 👉️ 10.0 (float) print(my_num // 5) # 👉️ 10 (int)
The "object is not subscriptable" TypeError basically means that the object cannot be accessed using square brackets.
You should only use square brackets to access subscriptable objects.
The subscriptable objects in Python are:
All other objects have to be converted to a subscriptable object by using the
list(),
tuple(), dict()
or str()
classes to
be able to use bracket notation.
Subscriptable objects implement the __getitem__
method whereas
non-subscriptable objects do not.
a_list = [1.1, 2.2, 3.3] # 👇️ <built-in method __getitem__ of list object at 0x7f71f3252640> print(a_list.__getitem__)