TypeError: ‘float’ object is not subscriptable
In this article we will learn about the TypeError: ‘float’ object is not subscriptable.
This error occurs when we try to access a float type object using index numbers.
Non subscriptable objects are those whose items can’t be accessed using index numbers. Example float, int, etc.
Examples of subscriptable objects are strings, lists, dictionaries. Since we can access items of a strings, lists or a dictionaries using index numbers. Float object is not indexable and thus we can’t access it using index numbers.
Let us understand it more with the help of an example.
Example:
Output:
In the above example we are trying to access the value at index 0 but as discussed above float is not indexable.
So accessing using index number will raise an error.
TypeError: ‘float’ object is not subscriptable.
Solution:
Do print(«area of the circle :»,area) instead of print(«area of the circle :»,area[0]) in line 10 of the code.
But what if we only want the value at index 0 and not the whole answer?
To solve this issue we can change the non subscriptable object to a subcriptable object.
In this case, we can try changing the float object to a string. As shown below.
Python — список ошибок и их исправление
Admin
02.08.2020 , обновлено: 09.08.2020
Python Errors
Список частых ошибок в Python и их исправление.
TypeError: object is not subscriptable
Ошибка, которая сообщает, что обращение идет к элементам не правильно. Возможно, это другой тип объекта, а не тот, который вам кажется. Проверить можно командой type().
Например, такое может быть, если это список (list), а в обращаетесь за элементом к словарю (dictionary).
TypeError: unsupported type for timedelta days component: str
Ожидается число, а передается в timedelta строка. Исправить просто, если уверены, что передается цифра, то достаточно явно преобразовать в число: int(days)
Failed execute: tuple index out of range
Означает что передаётся меньше данных, чем запрашивается.
ModuleNotFoundError: No module named ‘bot.bot_handler’; ‘bot’ is not a package
venv/bin/python bot/bot.py
Traceback (most recent call last):
File «bot/bot.py», line 4, in
from bot.bot_handler import BotHandler
File «bot/bot.py», line 4, in
from bot.bot_handler import BotHandler
ModuleNotFoundError: No module named ‘bot.bot_handler’; ‘bot’ is not a package
Конфилкт имени файла и директории — они не должны быть здесь одинаковыми. Поменяйте название директории или имени файла.
ValueError: a coroutine was expected, got
Traceback (most recent call last):
File «test.py», line 41, in
asyncio.run(update.update_operations)
File «/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/runners.py», line 37, in run
raise ValueError(«a coroutine was expected, got ».format(main))
ValueError: a coroutine was expected, got
Забыта скобки () у функции в команде asyncio.run(update.update_operations).
Читайте также
У сайта нет цели самоокупаться, поэтому на сайте нет рекламы. Но если вам пригодилась информация, можете лайкнуть страницу, оставить комментарий или отправить мне подарок на чашечку кофе.
‘float’ object is not subscriptable – Python Error
‘float’ object is not subscriptable is a Python type error which occurs when you try to access “index” on float variables.
This code will throw, ‘float’ object is not subscriptable error because here we have assigned a = 1.0 which means a is a float value. In the next line, we are printing the 0 th index of a , print(str(a[0])) , which is incorrect.
The error screen will look like this –

In type unsafe languages like javascript, php, python etc., we can assign int to float or int to string or string to boolean but it doesn’t work for arrays.
Arrays needs to be defined explicitly because, internally, they are not a value else the location of values. It means an array variable holds the address in memory location from where your first element starts.
So, the right way of implementing the above code is –
Python TypeError: ‘float’ object is not subscriptable Solution

In Python, there are 3 subscriptable objects list , string , and tuples , because all these objects support indexing to access their elements or characters. But Python object like float does not support indexing, and if we perform indexing to access any float value, we will receive TypeError: ‘float’ object is not subscriptable error in Python.
In this Python guide, we will walk through this Python error and discuss how to solve it. We will also discuss a common example where many new Python learners encounter this error. So now, let’s get started with the error statement.
Python Error: TypeError: ‘float’ object is not subscriptable
The Python error TypeError: ‘float’ object is not subscriptable statement is divided into two parts Error Type and Error Message
- Error Type ( TypeError ): TypeError occurs in Python when we perform an invalid operation on a Python data type object.
- Error message ( ‘float’ object is not subscriptable ): This error message is telling us that we are trying to access a floating-point value or variable as a subscritable object. And it generally occurs when we use indexing on a floating-point number.
Example
Common Error Scenario
Many new Python learners mistake the indexing operation of the string, list, and tuple with float numbers when they need to solve problems like extracting the first or last digit from a floating-point number.
Example
Output
Break the code
In the above example, we are getting this error because we tried to access the float number float_num first digit using indexing which is invalid in Python. We can not perform indexing on a floating-point number. That’s why Python threw the error ‘float’ object is not subscriptable .
Solution
To solve the above problem, we first need to change the floating-point number to a string so we can get the first digit using indexing. Then we will convert that first digit number back to an integer number using the Python int() function.
Example solution
Output
Wrapping Up!
The Python ‘float’ object is not subscriptable Error is a TypeError, that occurs when we try to access a floating-point number using indexing. Only Python lists, tuples, and string support indexing, and primitive values like int and float throw an error when we perform indexing on them.
If you are still getting this error in your Python program, you can share your code in the comment section, and we will try to help you in debugging.