Select Page

How to Solve Python TypeError: ‘float’ object is not subscriptable

by | Programming, Python, Tips

In Python, you cannot access values inside a float using indexing syntax. Floating-point numbers are single values, and indexing syntax is only suitable for subscriptable objects such as strings or lists. If you attempt to retrieve an individual number from a float, you will raise the “TypeError: ‘float’ object is not subscriptable”.

This tutorial will go through what the error means and the possible causes. We will explore examples and provide solutions for each of them.


TypeError: ‘float’ object is not subscriptable

Let’s break up the error message to understand what the error means. TypeError occurs whenever you attempt to use an illegal operation for a specific data type. The part “float object” tells us the error concerns an illegal operation for floating-point numbers.

The part “is not subscriptable” tells us we cannot access an element of the float object.

You cannot retrieve a specific value from a float. Floating-point numbers are not subscriptable objects.

Possible causes of “TypeError: ‘float’ object is not subscriptable” are:

  • Trying to access an item from a float
  • Trying to replace multiple items in a list

A subscriptable object is a container for other objects and implements the __getitem__() method. Examples of subscriptable objects include strings, lists, tuples, and dictionaries.

We can check if an object implements the __getitem__() method by listing its attributes with the dir function. Let’s call the dir function and pass a float and a string to see their attributes.

num = 5.1
print(dir(num))
['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__round__', '__rpow__', '__rsub__', '__rtruediv__', '__set_format__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']
string = "Python"
print(dir(string))
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

If you want to check if a specific attribute belongs to an object, you can check for membership using the in operator.

num = 5.1
print('__getitem__' in dir(num))
False

We can see that __getitem__ is not an attribute of the Float data type.

string = "Python"
print('__getitem__' in dir(string))
True

We can see that __getitem__ is an attribute of the String data type.

Example #1: Accessing an Item from a Float

You may encounter this error when using the indexing operation on float numbers, such as extracting the first or last digit from a floating-point number. Let’s look at an example of defining a floating-point number a try to access the first digit:

# floating point number

float_number = 456.0

# Access first digit of the floating number using indexing

first_digit = float_number[0]

# Print output

print(first_digit)

Let’s run the code to see what happens:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
first_digit = float_number[0]

TypeError: 'float' object is not subscriptable

The Python interpreter raises the TypeError because we are trying to access an element in a floating-point number.

Solution

We need to change the floating-point number to a subscriptable type to solve the problem. We will typecast the floating-point number to a string using the str() function. Once we have a string, we can access the first digit using indexing. Then we can convert the first digit string to an integer using the int() function.

# floating point number

float_number = 456.0

# Convert float to string

string_number = str(float_number)

# Access the first digit using indexing

first_digit = string_number[0]

# Convert first digit string value to integer

first_digit = int(first_digit)

# Print the first digit to console
print(f'The first digit of {float_number} is: {first_digit}')

Let’s run the code to get the result:

The first digit of  456.0 is: 4

Example #2: Replacing Multiple Items in a List

Slicing involves specifying a list of items in an object that you want to access or change. We can use list slicing to replace multiple items in a list. Let’s look at an example of a program that changes the weights of apples in grams to a particular weight. The first part of the program takes an input from the user asking for the default weight of an apple:

weight = input("Enter the default weight for an apple:  ")

We can then define a list of apple weights we need to change

apples = [96.3, 103.5, 74.5, 84.0, 90.2]

We can try to change the values in the list using indexing:

apples[0][1][2][3][4] = [float(weight)]*5
print(apples)

The above code resets the weights of the apples in the list at all index positions to the value of weight, a floating-point number. The weight is enclosed in square brackets and multiplied by five. This operation assigns five values to the five index positions in the apples list.

Let’s see what happens when we run the program:

Enter the default weight for an apple:  80
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
apples[0][1][2][3][4] = [float(weight)]*5

TypeError: 'float' object is not subscriptable

The Python interpreter raises the TypeError because the list only contains floats. Therefore, when we access the first element of the list with apples[0] we get a float. It follows that apples[0][1] is equivalent to accessing the element at the index position 1 in a float.

Solution

We can use the slicing syntax to update the list to solve this error.

weight = input("Enter the default weight for an apple:  ")

apples = [96.3, 103.5, 74.5, 84.0, 90.2]

apples[:4] = [float(weight)]*5

print(apples)
Enter the default weight for an apple:  80

[80.0, 80.0, 80.0, 80.0, 80.0]

The code retrieves all the items in the list from the index position 0 to 4 and assigns each value with the input value of weight. Go to the “How to Get a Substring From a String in Python” post to learn more about slicing.

Summary

Congratulations on reading to the end of this tutorial. The error “TypeError: ‘float’ object is not subscriptable” occurs when you try to access a floating-point number like a list. To solve this error, ensure you only use indexing or slicing syntax on a subscriptable object, like a list or a string. If you need to change multiple values in a list, ensure you use slicing instead of specifying a list of index numbers.

For further reading on TypeErrors, go to the articles:

To learn more about Python for data science and machine learning, you can go to the online courses page on Python for the most comprehensive courses.

Have fun and happy researching!

Research Scientist at Moogsoft | + posts

Suf is a research scientist at Moogsoft, specializing in Natural Language Processing and Complex Networks. Previously he was a Postdoctoral Research Fellow in Data Science working on adaptations of cutting-edge physics analysis techniques to data-intensive problems in industry. In another life, he was an experimental particle physicist working on the ATLAS Experiment of the Large Hadron Collider. His passion is to share his experience as an academic moving into industry while continuing to pursue research. Find out more about the creator of the Research Scientist Pod here and sign up to the mailing list here!