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!

Is your desired result:

[[1.5, 3.5, 2.1], [[], [], []], [[], [], []]]?

or is it ?

[[[1.5], [3.5], [2.1]], [[], [], []], [[], [], []]]?

because the second one is an equal data structure more likely what you want.

Then you need to not do:

survRates[0] = 1.5
survRates[1] = 3.5
survRates[2] = 2.5

Instead do:

survRates[0] = []
survRates[0][0] = 1.5
survRates[0][1] = 3.5
survRates[0][2] = 2.5

or since you have very specific requirements: it looks like you had a typo in your question: this probably what you really wanted.

survRates = [[[], [], []], [[], [], []], [[], [], []]]
survRates[0][0][0] = 1.5
survRates[0][0][1] = 3.5
survRates[0][0][2] = 2.5

That way each array will be an array with just one element… for I’m sure nefarious purposes.

You were not accurately describing what you wanted:

You wanted to set the position 0 (first element) in a list but not the list of survRates but instead the list in survRates's first element’s list (triply nested!). So for nested lists like survRates in order to access the first element of the first list you use: an_array[0][0][0] = just doing an_array[0] = or an_array[0][0] = will attempt to set the first element of survRates not survRates’ first list or that list’s first list.

This part generates: [[[], [], []], [[], [], []], [[], [], []]]

def gens():
    for i in range(totalGens):
        dataSet = []
        for j in range(3):
            dataSet.append([])
        newList.append(dataSet)
    print(newList)

If you want further help here explain what’s going on a bit deeper.

newAdults = juvs * survRates[0][0]

Having a hardcoded survRates[0][0] will return a list not an element probably unlikely that you want to multiply juvs by a list with 3 mathematical elements probably you want survRates[0][0][0] there.

UPDATE ==>
Since they’re saying they do particularly want it to have 1 array in the first data list and 3 arrays in each subsequent datalist:

gens() function should be modified:

def gens():
    for i in range(totalGens):
        dataSet = []
        for j in range(3):
            if i > 0:
                dataSet.append([])
        newList.append(dataSet)
    print(newList)

now we will have =>

[[], [[], [], []], [[], [], []]]

This part in the beginning of your post will still give an error:

survRates[0] = 1.5
survRates[1] = 3.5
survRates[2] = 2.5

But will work is:

 survRates[0][0] = 1.5
 survRates[0][1] = 3.5
 survRates[0][2] = 2.5

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

Ad

At Career Karma, our mission is to empower users to make confident decisions by providing a trustworthy and free directory of bootcamps and career resources. We believe in transparency and want to ensure that our users are aware of how we generate revenue to support our platform.

Career Karma recieves compensation from our bootcamp partners who are thoroughly vetted before being featured on our website. This commission is reinvested into growing the community to provide coaching at zero cost to their members.

It is important to note that our partnership agreements have no influence on our reviews, recommendations, or the rankings of the programs and services we feature. We remain committed to delivering objective and unbiased information to our users.

In our bootcamp directory, reviews are purely user-generated, based on the experiences and feedback shared by individuals who have attended the bootcamps. We believe that user-generated reviews offer valuable insights and diverse perspectives, helping our users make informed decisions about their educational and career journeys.

Find the right bootcamp for you

ck-logo

X

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.

‘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_Program\Sample_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_Program\Sample_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

Понравилась статья? Поделить с друзьями:
  • Float object is not iterable python ошибка
  • Float object is not callable ошибка
  • Filezilla выдает критическую ошибку
  • Filezilla ошибка 110
  • Filezilla невозможно подключиться к серверу ps3 ошибка