Float object is not subscriptable python ошибка

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.


Table of contents

  • TypeError: ‘float’ object is not subscriptable
  • Example #1: Accessing an Item from a Float
    • Solution
  • Example #2: Replacing Multiple Items in a List
    • Solution
  • Summary

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:

  • How to Solve Python TypeError: ‘str’ object does not support item assignment
  • How to Solve Python TypeError: ‘set’ object is not subscriptable
  • How to Solve Python TypeError: ‘_io.TextIOWrapper’ object is not subscriptable
  • How to Solve Python TypeError: ‘dict_items’ object is not subscriptable

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!

I got the same error below:

TypeError: ‘float’ object is not subscriptable

Because I set the number with a decimal part to MinMoneyValidator() and MaxMoneyValidator() respectively in MoneyField() with Django-money, as shown below:

# "models.py"

from django.db import models
from djmoney.models.fields import MoneyField
from djmoney.models.validators import MinMoneyValidator, MaxMoneyValidator 

class Product(models.Model):
    name = models.CharField(max_length=50)
    price = MoneyField( # Here
        max_digits=5, decimal_places=2, default=0, default_currency='USD',
        validators=[        # Here                    # Here
            MinMoneyValidator(0.00), MaxMoneyValidator(999.99),
        ]
    )

So, I set the number without a decimal part to MinMoneyValidator() and MaxMoneyValidator() respectively in MoneyField() as shown below, then the error above was solved:

# "models.py"

from django.db import models
from djmoney.models.fields import MoneyField
from djmoney.models.validators import MinMoneyValidator, MaxMoneyValidator

class Product(models.Model):
    name = models.CharField(max_length=50)
    price = MoneyField(
        max_digits=5, decimal_places=2, default=0, default_currency='USD',
        validators=[       # Here                 # Here
            MinMoneyValidator(0), MaxMoneyValidator(999),
        ]
    )

Values inside a float cannot be accessed using indexing syntax. This means that you cannot retrieve an individual number from a float. Otherwise, you’ll encounter a “typeerror: ‘float’ object is not subscriptable” in your program.

In this guide, we talk about what this error means and why you may see it. We walk through two example scenarios so you can figure out how to fix this problem.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

typeerror: ‘float’ object is not subscriptable

You can retrieve individual items from an iterable object. For instance, you can get one item from a Python list, or one item from a dictionary. This is because iterable objects contain a list of objects. These objects are accessed using indexing.

You cannot retrieve a particular value from inside a float. Floating-point numbers, like integers, are not iterable objects.

The “typeerror: ‘float’ object is not subscriptable” is commonly caused by:

  • Trying to access a particular value from a floating-point number
  • Using the wrong syntax to replace multiple items in a list

Let’s walk through each of these scenarios.

Scenario #1: Accessing an Item from a Float

We’re building a program that checks if a ticket holder in a raffle is a winner. If a user’s ticket number starts with 1 and ends in 7, they are a winner.

Let’s start by asking a user to insert a ticket number that should be checked:

ticket_number = float(input("Enter a ticket number: "))

We’ve converted this value to a float because it is a number.

Next, we use indexing syntax to retrieve the first and last numbers on a ticket:

first = ticket_number[0]
last = ticket_number[-1]

The first item in our ticket number is at the index position 0; the last item is at the index position -1. Next, we use an “if” statement to check if a user is a winner:

if first == "1" and last == "7":
	print("You are a winner!")
else:
	print("You are not a winner.")

If the value of “first” is equal to “1” and the value of “last” is equal to “7”, our “if” statement will run and inform a user they have won. Otherwise, our “else” statement will run, which will inform a user that they are not a winner.

Let’s run our code:

Enter a ticket number: 23
Traceback (most recent call last):
  File "main.py", line 3, in <module>
	first = ticket_number[0]
TypeError: 'float' object is not subscriptable

Our code does not work. This is because ticket numbers are stored as a float. We cannot use indexing syntax to retrieve individual values from a float.

To solve this error, we remove the float() conversion from our first line of code:

ticket_number = input("Enter a ticket number: ")

The input() method returns a string. We can manipulate a string using indexing, unlike a floating-point value. Let’s run our code again:

Enter a ticket number: 23
You are not a winner.

Our code appears to work successfully. Let’s test our code on a winning ticket:

Enter a ticket number: 117
You are a winner!

Our code works whether a ticket is a winner or not.

Scenario #2: Replacing Multiple Items

List slicing allows you to replace multiple items in a list. Slicing is where you specify a list of items in an iterable that you want to access or change.

Let’s build a program that resets the prices of all products in a list of donuts. We must build this program because a store is doing a “Donut Day” promotion where every donut is a particular price. We start by asking the user for the new price of donuts:

price = input("Enter the price of the donuts: ")

Next, we define a list of the current prices of donuts that we must change:

donuts = [2.50, 2.75, 1.80, 1.75, 2.60]

Now that we have these values, we’re ready to change our list. We can do this using indexing:

donuts[0][1][2][3][4] = [float(price)] * 5
print(donuts)

This code resets the values in the “donuts” list at the index positions 0, 1, 2, 3, and 4 to the value of “price”. We’ve converted the value of “price” to a floating point number.

We’ve then enclosed the price in square brackets and multiplied it by five. This creates a list of values which we can assign to our “donuts” list.

Finally, we print the new list of prices to the console. Let’s run our code:

Enter the price of the donuts: 2.50
Traceback (most recent call last):
  File "main.py", line 3, in <module>
	donuts[0][1][2][3][4] = [float(price)] * 5
TypeError: 'float' object is not subscriptable

When our code tries to change the values in the “donuts” list, an error is returned. Our code tries to retrieve the item at the index position [0][1][2][3][4]. This does not exist in our list because our list only contains floats. To solve this error, use slicing syntax to update our list. 

donuts[0:5] = [float(price)] * 5

This code retrieves all the items in our list from the range of 0 to 5 (exclusive of 5). Then, we assign each value the value of “price”. Let’s try our new code:

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

Enter the price of the donuts: 2.50
[2.5, 2.5, 2.5, 2.5, 2.5]

Our code successfully replaces all the items in our list.

Conclusion

The “typeerror: ‘float’ object is not subscriptable” error occurs when you try to access items from a floating point number as if the number is indexed.

To solve this error, make sure you only use indexing or slicing syntax on a list of iterable objects. If you are trying to change multiple values in a list, make sure you use slicing to do so instead of specifying a list of index numbers whose values you want to change.

Now you’re ready to solve this error in your own code.

‘float’ object is not subscriptable is a general python error message which can occur when you try to perform any kind of indexing operation on float type object.

In this article we will study different aspects of this error message as such what is meant by ‘float’ object is not subscriptable? Why you are getting this error message and how to resolve it. Go through this article thoroughly to get rid of this error message.

'float' object is not subscriptable

Let’s try to decode the error message. We have divided the error message into three parts as below for better understanding:

TypeError: It means you are trying to perform an invalid operation on the variable of a particular type. If the operation is not supported by the type of variable then it will give TypeError.

float: float is a type of object. It tells us that an illegal operation is performed on the float type of object.

object is not subscriptable: It tells us that float type of objects are not subscriptable, which means you cannot perform indexing operation on float type of object.

What are subscriptable and non- subscriptable objects?

Subscriptable Objects:

If objects store multiple values and these values can be accessed using indexing then these are called subscriptable objects.

Subscriptable objects internally implements __getitem__() method. We can access elements of subscriptable objects using the index as shown below:

# Sample Python program to access first element from the list
quad =['United States','Japan','India','Australia']
print(quad[0])

When executed above code will give the following result.

United States

Here quad is a list type of object. We accessed the first element of a quad list using quad[0]

Strings, Lists, Tuples, and Dictionaries are the subscriptable objects in Python on which you can perform the indexing operation.

Non-Subscriptable Objects:

If object stores single or whole value then these are called non-subscriptable objects.

We cannot access elements of non-subscriptable objects using the index position. It will result in an error message saying the object is not subscriptable.

int and float are the Non-Subscriptables objects on which we cannot perform indexing operations.

Why you are getting TypeError: ‘float’ object is not subscriptable?

You are getting ‘float’ object is not subscriptable means in your code you are trying to get the value of a float type of object using indexing which is an invalid operation.

A float is a non-subscriptable object. Indexing operation is not supported on non-subscriptable objects.

Either you have mistakenly tried to access the value of a float variable using an index or if you want to access particular positions element of the value and directly used an index to get the element of value. That results in the TypeError: ‘float’ object is not subscriptable error message.

How to solve TypeError: ‘float’ object is not subscriptable?

Here we will see two scenarios where this error can occur and the way to resolve it. So don’t waste your time and start evaluating.

1. Access the first digit of a float value

Below sample code calculates the area of a rectangle by taking length and width as an input from the user. Once the area is calculated code tries to get the first digit of a calculated area using the index position.

# File: Sample_Program_1.py
# Sample Python program to calculate area of rectangle

# get input arguments from user for length and width 
length = float(input("Enter the length of a rectangle: "))
width = float(input("Enter the width of a rectangle: "))

# Area of rectangle is muliplication of width and length
area = length*width

#print first element of areaString values
print("Area of rectangle: " + str(area))
print("The first digit of an area: " + str(area[0]))

When the above code is executed it gives the following error message.

C:Sample_Program>python Sample_Program_1.py
Enter the length of a rectangle: 24
Enter the width of a rectangle: 17
Area of rectangle: 408.0
Traceback (most recent call last):
File “C:Sample_ProgramSample_Program_1.py”, line 13, in
print(“The first digit of an area: ” + str(area[0]))
TypeError: ‘float’ object is not subscriptable

We are getting this error message when the code tries to get the first digit of a calculated area using index i.e. area[0]. An area is a float type of object and it’s non-subscriptable, hence indexing operation cannot be performed on a float object.

Solution:

If you want to get the first digit of a calculated area then convert that float object into a string object first and then get the first character of string using index position as shown below.

# File: Sample_Program_1.py
# Sample Python program to perform append operation on the list

# get input arguments from user for length and width 
length = float(input("Enter length of a rectangle: "))
width = float(input("Enter width of a rectangle: "))

# Area of rectangle is muliplication of width and length
area = length*width

# Convert area into string
areaString = str(area)

#print first element of areaString values
print("Area of rectangle: " + areaString)
print("The first digit of an area: " + areaString[0])

When the above code is executed it will give the following result.

C:Sample_Program>python Sample_Program_1.py
Enter the length of a rectangle: 24
Enter the width of a rectangle: 17
Area of rectangle: 408.0
The first digit of an area: 4

Note: string is subscriptable object hence it supports index operation

2. Accessing 2D values from a 1D list

In the following example, we are trying to access 2D values from a 1D list.

# File: Sample_Program_2.py
# Sample Python program to access values from the list object

# List object with some default values
valueList = [35.5, 41.956, 43.215, 54.884, 57.149]

#For loop to access all values of list object
for i in range(1, len(valueList)):
  iCnt = valueList[0][i]
  print(iCnt)

When the above code is executed it will give the following error message.

C:Sample_Program>python Sample_Program_2.py
Traceback (most recent call last):
File “C:Sample_ProgramSample_Program_2.py”, line 9, in
iCnt = valueList[0][i]
TypeError: ‘float’ object is not subscriptable

Solution:

Access values from a 1D list using the 1D index position as shown below:

# File: Sample_Program_2.py
# Sample Python program to access values from the list object

# List object with some default values
valueList = [35.5, 41.956, 43.215, 54.884, 57.149]

#For loop to access all the values of list object
for i in range(1, len(valueList)):
  iCnt = valueList[0],valueList[i]
  print(iCnt)

When the above code is executed it will give the following result.

C:Sample_Program>python Sample_Program_2.py
(35.5, 41.956)
(35.5, 43.215)
(35.5, 54.884)
(35.5, 57.149)

Conclusion:

We hope this article was informative and you got a clear idea about what are subscriptable objects and non-subscriptable objects. Always be careful while accessing the index value of variables.  If you again face the same issue then make sure to validate all the code lines where you are trying to access the index value of an object.

For now, we are sure that you are able to get rid of an error message using the above methods. If you are still facing the issue then please do mention it in the comment section or you can reach out to us using the contact form. You can also contact us using our official mail id i.e. hello.technolads@gmail.com

Further Read:

TypeError: ‘builtin_function_or_method’ object is not subscriptable

If you are working with Python, you may encounter the error message “TypeError: ‘float’ object is not subscriptable” when trying to access a value at an index or slicing a float variable. This error occurs because float objects are not subscriptable, meaning you cannot access individual elements of a float object like you can with a list or a string.

fix typeerror float object is not subscriptable in python

In this tutorial, we will explore the causes of this error and provide several solutions to fix it. We will also discuss some best practices to avoid this error in the future. So, let’s get started!

Understanding the TypeError: 'float' object is not subscriptable error

The error message here is quite helpful. It tells us that we’re trying to use a float as a subscriptible object (for example, a list, string, tuple, etc.) using the square brackets notation [] to retrieve a specific element or a slice of elements. A float object represents a floating point value and not a sequence and thus, we cannot really use them as subscriptible objects. If you try to do so, you’ll get this error.

Let’s look at an example.

# float variable
temperature = 98.7
# using float as a subscriptable object
print(temperature[0])

Output:

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

Cell In[3], line 4
      2 temperature = 98.7
      3 # using float as a subscriptable object
----> 4 print(temperature[0])

TypeError: 'float' object is not subscriptable

In the above example, we created a float variable temperature which stores the float value 98.7. We then tried to access the value at index 0 in the variable temperature and we get the error TypeError: 'float' object is not subscriptable.

You’ll get the same error if you try to perform a slice operation on an integer value.

# float variable
temperature = 98.7
# using float as a subscriptable object
print(temperature[0:3])

Output:

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

Cell In[4], line 4
      2 temperature = 98.7
      3 # using float as a subscriptable object
----> 4 print(temperature[0:3])

TypeError: 'float' object is not subscriptable

In the above scenarios, we are using the float variable as a subscriptable object which is not allowed (and doesn’t really make sense) since a float value represents a single value and not a sequence of values and thus a TypeError is raised.

Fixing the error

To fix this error, you can either not use float objects as subscriptable or use a subscriptable object like a list instead.

Let’s revisit the examples from above and fix those errors.

# float variable
temperature = 98.7
# using float as a subscriptable object
print(temperature)

Output:

98.7

Here, we are not using the float value as subscriptable object and instead directly printing its value. You can see that we don’t get an error.

# list of temperatures
temperatures = [91.1, 77.3, 82.0, 102.3, 89.6]
# using list as a subscriptable object
print(temperatures[0:3])

Output:

[91.1, 77.3, 82.0]

Here, instead of using a float value, we are using a which that is subscriptable, and thus performing operations like slicing or accessing a value at an index won’t result in this TypeError.

Note that the solution to correct this error will depend on your use case and what you’re trying to achieve.

Conclusion

The “TypeError: ‘int’ object is not subscriptable” error occurs when we try to access an index of a float object or slice a float object, which is not possible as floats are not subscriptable. To fix this error, you can choose to not perform such operations on floats or use a subscriptable type like a list or a string instead.

You might also be interested in –

  • How to Fix – TypeError ‘set’ object is not subscriptable
  • How to Fix – TypeError ‘int’ object is not subscriptable
  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

    View all posts

Понравилась статья? Поделить с друзьями:
  • Fondital antea ошибка е52
  • Fonbet код ошибки 101
  • Fona x70 ошибка a02
  • Fona x70 коды ошибок
  • Following deviation is too large ошибка