BugHunt

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

You used a float as an index. In Python 3, / always produces a float — even when the result looks whole.

PythonType errors

What it means

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.

Common causes

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.

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.

Other common errors