TypeError: list indices must be integers, not float
Asked Answered
W

7

30

I have a python 3.x program that is producing an error:

def main():
    names = ['Ava Fischer', 'Bob White', 'Chris Rich', 'Danielle Porter',
             'Gordon Pike', 'Hannah Beauregard', 'Matt Hoyle',
             'Ross Harrison', 'Sasha Ricci', 'Xavier Adams']

    entered = input('Enter the name of whom you would you like to search for:')
    binary_search(names, entered)

    if position == -1:
        print("Sorry the name entered is not part of the list.")
    else:
        print(entered, " is part of the list and is number ", position, " on the list.")
    input('Press<enter>')

def binary_search(names, entered):
    first = 0
    last = len(names) - 1
    position = -1
    found = False

    while not found and first <= last:
        middle = (first + last) / 2

        if names[middle] == entered:
            found = True
            position = middle
        elif names[middle] > entered:
            last = middle - 1
        else:
            first = middle + 1

    return position

main()

Error is:

TypeError: list indices must be integers, not float

I am having trouble understanding what this error message means.

Woodenware answered 13/11, 2012 at 4:59 Comment(1)
Please give the complete error message including the traceback.Donatist
A
73

It looks like you are using Python 3.x. One of the important differences in Python 3.x is the way division is handled. When you do x / y, an integer is returned in Python 2.x because the decimal is truncated (floor division). However in 3.x, the / operator performs 'true' division, resulting in a float instead of an integer (e.g. 1 / 2 = 0.5). What this means is that your are now trying to use a float to reference a position in a list (e.g. my_list[0.5] or even my_list[1.0]), which will not work as Python is expecting an integer. Therefore you may first want to try using middle = (first + last) // 2, adjusting so that the result returns what you expect. The // indicates floor division in Python 3.x.

Amorphous answered 13/11, 2012 at 5:7 Comment(0)
T
3

Kinda late to the party but you could also use:

middle = int((first + last) / 2)

In any case why you are getting your error is perfectly explained in RocketDonkey answer.

For your code to work you should also set:

position = binary_search(names, entered)

as Hugo Ferreira mentioned.

Also check this question: What is the difference between '/' and '//' when used for division?

Tonie answered 16/12, 2019 at 23:40 Comment(0)
S
1

I had this problem when using ANN and PyBrain on function testOnData().

So, I solved this problem putting "//" instead "/" inside the index on backprop.py source code.

I changed:

print(('Max error:', 
    max(ponderatedErrors), 
    'Median error:',
     sorted(ponderatedErrors)[len(errors) / 2])) # <-- Error area 

To:

print(('Max error:', 
    max(ponderatedErrors), 
    'Median error:',
     sorted(ponderatedErrors)[len(errors) // 2])) # <-- SOLVED. Truncated

I hope it will help you.

Stibnite answered 18/9, 2018 at 8:6 Comment(0)
E
0

I can be wrong but this line:

binary_search(names, entered)

would not be

position = binary_search(names, entered)
Estranged answered 30/3, 2017 at 11:34 Comment(0)
M
0

Error is in the division operator of the binary search function, it should be // instead of /

Aka:

mid = (low + high) // 2
Munmro answered 21/4, 2022 at 18:36 Comment(0)
R
0

This should solve the problem also. Although what others have explained it well. Its always better to do this to debug what could have gone wrong.

names[int(middle)]

Reis answered 9/4, 2023 at 19:3 Comment(0)
A
-1

if first = 0 and last = 6 then using / operator you will get 3.0 so your compiler gives error therefore you need to typecast it.

middle = int((first + last) / 2)
Appall answered 8/1, 2022 at 13:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.