Solving 'Float Object Not Subscriptable' Error in Python

PYTHON Published Updated 3 mins read By Leon Wei
Solving 'Float Object Not Subscriptable' Error in Python cover image

Quick summary

Summarize this blog with AI

TypeError: 'float' object is not subscriptable means the object immediately before [...] is a floating-point number. A float is one scalar value, not a sequence of elements. The repair depends on whether you intended to use that number directly, select a number from a collection, or work with its text representation.

These independent diagnostic examples were tested with Python 3.12.14. They print exception types deliberately so you can compare failures without stopping the lesson.

Identify the object being indexed

price = 7.89
print(type(price).__name__)
try:
    print(price[0])
except TypeError as exc:
    print(str(exc))

Expected output:

float
'float' object is not subscriptable

The index 0 is not the problem here. price is. Read the traceback's failing line, then inspect the object to the left of the brackets and the function or assignment that produced it. Avoid printing sensitive values while debugging production data; a type or a deliberately small synthetic fixture is usually enough.

Repair the data operation

Use a scalar without brackets

If the calculation needs one price, use the float directly. There is no first element to extract.

price = 7.89
quantity = 2
print(round(price * quantity, 2))

Expected output:

15.78

Binary floating-point has rounding limits. For exact decimal money rules, choose a decimal representation and an explicit rounding policy; changing indexing syntax does not address that separate requirement.

Select a value from an actual collection

prices = [7.89, 12.50, 3.25]
first_price = prices[0]
print(first_price)
print(type(first_price).__name__)

Expected output:

7.89
float

After prices[0], the result is already a float. Writing prices[0][0] tries to index that scalar again. If a function unexpectedly returns a float instead of a list or record, correct its return contract or the caller's assumption.

Convert to text only when the task is textual

price = 7.89
label = f'{price:.2f}'
print(label)
print(label[0])

Expected output:

7.89
7

The final value is the string '7', not the numeric first component of a float. Negative numbers, scientific notation, and formatting choices make text positions unsuitable for general numeric calculations.

A float index is a different error

items[7.89] fails because a list index must be an integer or slice. Blindly replacing it with items[int(7.89)] truncates the value to 7 and can introduce IndexError. It does not fix indexing a float.

items = ['a', 'b', 'c']
for index in (7.89, int(7.89)):
    try:
        print(items[index])
    except (TypeError, IndexError) as exc:
        print(type(exc).__name__)

Expected output:

TypeError
IndexError

If an external interface defines an index as a decimal integer string, validate that exact contract. This example accepts only ASCII digits and non-negative, in-range positions. It intentionally rejects '1.0', signs, and surrounding spaces instead of silently guessing the user's meaning.

def select_item(items, raw_index):
    if not isinstance(raw_index, str):
        raise TypeError('index must be text')
    if not raw_index or not raw_index.isascii() or not raw_index.isdecimal():
        raise ValueError('index must contain ASCII digits only')
    index = int(raw_index)
    if index >= len(items):
        raise IndexError('index is outside the collection')
    return items[index]

print(select_item(['a', 'b', 'c'], '1'))
for raw_index in ('7.89', '7', '-1'):
    try:
        select_item(['a', 'b', 'c'], raw_index)
    except (ValueError, IndexError) as exc:
        print(raw_index, type(exc).__name__)

Expected output:

b
7.89 ValueError
7 IndexError
-1 ValueError

Test the contract at the boundary

Give scalars and collections distinct names, document function return types, and test both ordinary and empty input. Do not catch every exception and return a made-up value: that hides a shape or type error from downstream calculations. Handle invalid user input where the application can explain the problem; let unexpected programming errors retain their traceback.

For a broader debugging sequence, continue with the Python syntax and error-handling guide. See Python's exception reference for the distinctions between TypeError, ValueError, and IndexError.

Interview Prep

Begin Your SQL, Python, and R Journey

Master 230 interview-style coding questions and build the data skills needed for analyst, scientist, and engineering roles.

Related Articles

All Articles