TryBugHunt

TypeError: list indices must be integers or slices, not float

TypeError: list indices must be integers or slices, not float in Python means you used a float as an index. In Python 3, / always produces a float — even when the result looks whole.

PythonPattern: Type errors

How do I fix TypeError: list indices must be integers or slices, not float?

To fix TypeError: list indices must be integers or slices, not float in Python, locate the line causing the error and check the values right before it runs. Most occurrences happen because of dividing to find a midpoint. Apply a defensive check or safe fallback, make sure collections or objects exist before access, and verify return values from upstream functions.

1. Inspect bounds & typesPrint or inspect collection sizes and verify variables are not empty or None/undefined.
2. Guard with safe accessUse optional chaining (?.), dictionary get(), or guard conditions before dereferencing.
3. Trace upstream originsFind where the value was instantiated or returned rather than only patching the symptom.

What does TypeError: list indices must be integers or slices, not float mean?

Python 3 changed / to true division, so 4 / 2 is 2.0, not 2. A float can never be a list index however round it looks. // is floor division and returns an int for int operands.

Why does TypeError: list indices must be integers or slices, not float happen?

1. Dividing to find a midpoint

len(items) / 2 is a float. This is the single most common source of this error.

Breaks

middle = items[len(items) / 2]

Works

middle = items[len(items) // 2]

2. Code written for Python 2

In Python 2, / on two ints did floor division. Older tutorials still teach it that way.

Breaks

half = items[count / 2]

Works

half = items[count // 2]

How to find it in your own code

Use // whenever the result is going to be an index. If a value must be an int, int() it explicitly rather than hoping the arithmetic keeps it whole.

Try it: fix this bug

easy

middle_item([1, 2, 3]) crashes: TypeError: list indices must be integers or slices, not float.

def middle_item(items):
    return items[len(items) / 2]
Open with hintsRuns in your browser. No account needed.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Related error guides

View all type errors →