
Problem Formulation
Consider the following minimal example where a TypeError: 'float' object is not subscriptable
occurs:
variable = 42.42 x = variable[0]
This yields the following output:
Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 2, in <module> x = variable[0] TypeError: 'float' object is not subscriptable
Solution Overview
Python raises the TypeError: 'float' object is not subscriptable
if you use indexing or slicing with the square bracket notation on a float variable that is not indexable.
However, the float class doesn’t define the __getitem__()
method.
variable = 1.23 variable[0] # TypeError! variable[1:10] # TypeError! variable[-1] # TypeError!
You can fix this error by
- converting the float to a string using the
str()
function because strings are subscriptable, - removing the indexing or slicing call,
- defining a dummy
__getitem__()
method for a custom float wrapper class.
π Related Tutorials: Check out our tutorials on indexing and slicing on the Finxter blog to improve your skills!
Method 1: Convert Float to a String
If you want to access individual digits of the float value, consider converting the float to a string using the str()
built-in function. A string is subscriptable so the error will not occur when trying to index or slice the converted string.
variable = 42.42 my_string = str(variable) print(my_string[0]) # 4 print(my_string[1:4]) # 2.4 print(my_string[:-1]) # 42.4
Method 2: Put Float Into List
A simple way to resolve this error is to put the float into a list that is subscriptable—that is you can use indexing or slicing on lists that define the __getitem__()
magic method.
variable = [42.42] x = variable[0] print(x) # 42.42
Or another example with multiple float values—now it starts to actually make sense:
sensor = [1.2, 2.1, 3.2, 0.9, 4.2] print(sensor[0]) # 1.2 print(sensor[-1]) # 4.2 print(sensor[:]) # [1.2, 2.1, 3.2, 0.9, 4.2]
Method 3: Define the __getitem__() Magic Method
You can also define your own wrapper type around the float variable that defines a (dummy) method for __getitem__()
so that every indexing or slicing operation returns the same float.
class MyFloat: def __init__(self, f): self.f = f def __getitem__(self, index): return self.f my_float = MyFloat(42.42) print(my_float[0]) # 42.42 print(my_float[100]) # 42.42
This hack is generally not recommended, I included it just for comprehensibility and to teach you something new. π
Summary
The error message “TypeError: 'float' object is not subscriptable
” happens if you access a float f
like a list such as f[0]
. To solve this error, avoid using slicing or indexing on a float but use a subscriptable object such as lists or strings.