TypeError: 'float' object is not subscriptable in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
5 min

banner

# TypeError: 'float' object is not subscriptable in Python

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

typeerror float object is not subscriptable

Here are 2 examples of how the error occurs.

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

# Convert the float to a string before accessing it 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.

main.py
my_float = 3.123456 result = str(my_float) print(result[0]) # 👉️ 3 print(result[2]) # 👉️ 1 print(result[:3]) # 👉️ 3.1

convert float to string before accessing it at index

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:

  • a string at a specific index
  • a list at a specific index
  • a tuple at a specific index
  • a specific key in a dictionary

# Track down where the variable got assigned a float

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.

main.py
my_list = 3.123456 # ⛔️ TypeError: 'float' object is not subscriptable print(my_list[0])

track down where variable got assigned float

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.

# Working with lists that contain floating-point numbers

The error also commonly occurs when working with lists that contain floating-point numbers.

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

# Convert the list item to a string before accessing a digit

If you need to access a specific digit of a list element, convert the element to a string.

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

convert list item to string before accessing digit

We used the str() class to convert the float to a string before accessing the first character (index 0).

# Replacing multiple values in a list

If you need to replace multiple values in a list, use list slicing.

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

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

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

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

# Updating each value in the list separately

You can also update each value in the list using a separate statement.

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

updating each value in list separately

The code sample updates the second and third list elements.

# Using a formatted string literal to convert the float to a string

You can also use a formatted string literal to convert a float to a string to be able to access it at an index.

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

using formatted string literal to convert float to string

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

main.py
var1 = 'bobby' var2 = 'hadz' result = f'{var1}{var2}' print(result) # 👉️ bobbyhadz

Make sure to wrap expressions in curly braces - {expression}.

You can also use a formatted string literal if you need to round a float to N decimal places.
main.py
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.

# Taking a floating-point number from user input

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.

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

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

  • list
  • tuple
  • dictionary
  • string

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.

main.py
a_list = [1.1, 2.2, 3.3] # 👇️ <built-in method __getitem__ of list object at 0x7f71f3252640> print(a_list.__getitem__)
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.