The “TypeError: list indices must be integers or slices, not float” error occurs when you try to access an item from a list using a floating-point number. To solve this error, make sure you only use integers to access items in a list by their index value.,Lists are indexed using index numbers. These numbers are integer values. If you try to access an item from a list using a floating-point number, the “TypeError: list indices must be integers or slices, not float” error will be raised.,You cannot retrieve items from a list using floating-point numbers. Floating-point numbers are a different data type. As a result, they are treated differently by Python. Lists expect an integer index number because lists are indexed using integers.,When an item is added to a list, the item is assigned an index value. Index values start from zero and increment by one for each new item in the list. This makes it easy to access individual items. The first item in a list has the index 0, the second has the index 1, and so on.
participants = [
["Alex Rogers", 5, 2],
["Linda Patterson", 3, 4],
["Ruby Spencer", 1, 6]
]
player_to_find = float(input("Enter the leaderboard position of the player you want to find: "))
player_info = participants[player_to_find - 1]
print("Name: {}".format(player_info[0]))
print("Wins: {}".format(player_info[1]))
print("Losses: {}".format(player_info[2]))
Enter the leaderboard position of the player you want to find: 2
Traceback (most recent call last):
File "main.py", line 9, in <module>
player_info = participants[player_to_find + 1]
TypeError: list indices must be integers or slices, not float
player_to_find = int(input("Enter the leaderboard position of the player you want to find: "))
Last updated: Apr 20, 2022
Copied!my_list = ['a', 'b', 'c'] my_float = 1.0 #⛔️ TypeError: list indices must be integers or slices, not float result = my_list[my_float]
Copied!my_list = ['a', 'b', 'c'] my_float = 1.0 #✅ convert float to int result = my_list[int(my_float)] print(result) #👉️ 'b'
Copied!my_list = ['a', 'b', 'c'] my_float = 4 / 2 print(my_float) #👉️ 2.0 result = my_list[int(my_float)] print(result) #👉️ 'c'
Copied!my_list = ['a', 'b', 'c'] my_int = 4 // 2 print(my_int) #👉️ 2 result = my_list[my_int] print(result) #👉️ 'c'
Copied!my_list = ['a', 'b', 'c', 'd', 'e'] print(my_list[0: 3]) #👉️['a', 'b', 'c'] print(my_list[3: ]) #👉️['d', 'e']
Copied!my_float = 3.14
print(type(my_float)) # 👉️ <class 'float'>
print(isinstance(my_float, float)) # 👉️ True
For your code to work you should also set:
position = binary_search(names, entered)
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 can be wrong but this line:
binary_search(names, entered)
would not be
position = binary_search(names, entered)
Aka:
mid = (low + high) // 2
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)
Vinay KhatriLast updated on July 19, 2022
Example
# list my_list = [10, 20, 30, 40, 50] # float number index = 2.0 print(my_list[index])
Output
Traceback(most recent call last):
File "main.py", line 8, in
print(my_list[index])
TypeError: list indices must be integers or slices, not float
Example
top3 = [ ['1', 'Rahul', '990', '17'], ['2', 'Ravi', '987', '17'], ['3', 'Anil', '967', '17'], ] # convert the input number in float rank = float(input("Enter a Number between 0 to 2: ")) print("Rank:", top3[rank][0]) print("Name:", top3[rank][1]) print("Marks", top3[rank][2]) print("Age", top3[rank][3])
Hello, I keep getting ‘Your code threw a “list indices must be integers, not float” error’ error. I checked it several times and can’t see where it is not an integer..,We need to find the floated average of two numbers, because there is no static calculated median in an even amount of numbers.,![1] when you post code, highlight it all and click the {}-button in order to preserve formatting and enable others to run your code without having to spend time guessing what your indentation looks like [1]: http://i.imgur.com/FZyPDjY.png,in python 3.x however, int/int gets you a float - this is a difference to keep in mind, most other differences will be cause obvious and googleable errors
def median(list):
b = len(list)
if b % 2 != 0:
a = list[(b / 2) - 0.5]
else:
a = (list[(b / 2)] + list[(b / 2) - 1]) / 2
return a
Shorthand:
def median(List):
newList = sorted(List)
count = len(newList)
if count % 2 == 0:
return (float(newList[(count / 2)]) + float(newList[((count / 2) - 1)])) / 2
else:
return float(newList[(count / 2)])
print median(oldList)
Demonstration:
oldList = [3, 2, 1, 4, 5, 6, 42, 51, 23, 52, 3, 6, 1, 2, 4, 6, 412, 54, 22, 125, 33]
def median(List):
newList = sorted(List)
count = len(newList)
high = float(newList[(count / 2)])
low = float(newList[((count / 2) - 1)])
print "Here is our organized list", newList
print "Here are how many items we have within that list", count
print "Here we have our median on odd lists as well as our upper number for even ones", high
print "Here we have our median number for odd lists", low
print "Here we have a combined average of high and low", (high + low) / 2
if count % 2 == 0:
return (high + low) / 2
else:
return high
print median(oldList), "Final Answer"
reproduce the error to to get the full message:
median([1])
-
Traceback (most recent call last):
File "C:\Python27\scratchpad.py", line 10, in <module>
median([1])
File "C:\Python27\scratchpad.py", line 4, in median
a = list[(b / 2) - 0.5]
TypeError: list indices must be integers, not float
error says line 4, insert prints to figure out what it is you are trying to do:
def median(list):
b = len(list)
if b % 2 != 0:
print 'b is:', b, 'index being accessed:', (b / 2) - 0.5
a = list[(b / 2) - 0.5]
else:
a = (list[(b / 2)] + list[(b / 2) - 1]) / 2
return a
median([1])
But I get an exception TypeError: list indices must be integers or slices, not float when I run code above.,ImportError: cannot import name 'get_config' from 'tensorflow.python.eager.context',TypeError: cannot unpack non-iterable NoneType object in Python, Y -3 Yusuf Bashir Sep 07 2021This error throw is related to set an index to get an item from an array.You need to change the line code below: middle = (first + last) / 2 To middle = int((first + last) / 2) And it resolved for you.
position = 0
def main():
names = ['A Name', 'B Name', 'C meah', 'D Name',
'E Name', 'G Name', 'M Fullname',
'Ross Name', 'Sasha Name', 'Xavier Name']
entered = input('Enter name to search:')
binary_search(names, entered)
if position == -1:
print("Name entered is not found.")
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()
Enter name to search:A Name
Traceback (most recent call last):
File "main.py", line 35, in <module>
main()
File "main.py", line 8, in main
binary_search(names, entered)
File "main.py", line 25, in binary_search
if names[middle] == entered:
TypeError: list indices must be integers or slices, not float
middle = (first + last) / 2
middle = int((first + last) / 2)
This type error occurs when indexing a list with anything other than integers or slices, as the error mentions. Usually, the most straightforward method for solving this problem is to convert any relevant values to integer type using the int() function. Something else to watch out for is accidentally using list values to index a list, which also gives us the type error.,Today we'll be looking at some of the issues you may encounter when using list indexing. Specifically, we'll focus on the error TypeError: list indices must be integers or slices, not str, with some practical examples of where this error could occur and how to solve it.,This error occurs when using a string for list indexing instead of indices or slices. For a better understanding of list indexing, see the image below, which shows an example list labeled with the index values:,Using indices refers to the use of an integer to return a specific list value. For an example, see the following code, which returns the item in the list with an index of 4:
TypeError: list indices must be integers or slices, not str
Learn Data Science with
value = example_list[4] # returns 8 Learn Data Science with
value_list_1 = example_list[4: 7] # returns indexes 4, 5 and 6[8, 1, 4] value_list_2 = example_list[1: 7: 2] # returns indexes 1, 3 and 5[7, 0, 1] Learn Data Science with
favourite_three_franchises = ['Call of Duty', 'Final Fantasy', 'Mass Effect']
choice = input('Which list index would you like to pick (0, 1, or 2)? ')
print(favourite_three_franchises[choice])
Learn Data Science with
Which list index would you like to pick(0, 1, or 2) ? 0
Learn Data Science with
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-34186a0c8775> in <module>
3 choice = input('Which list index would you like to pick (0, 1, or 2)? ')
4
----> 5 print(favourite_three_franchises[choice])
TypeError: list indices must be integers or slices, not str
Learn Data Science with
In the above example, we have declared a list with the name “list1” and an index variable to access the value of list with the name ‘index’ and given value “1” as a string, not an integer.,As we know that the index of every list is an integer, and in the above example, we have declared index value as a string.,If you are using a variable for specifying the index of a list element, make sure it has an integer value. Otherwise, you can directly access an element using the indices. ,Each element in a list in Python has a unique position. This position is defined by an index. These indexes are always defined using integers. You might declare a variable that has the index value of a list element. But if this variable does not have an integer value and instead has a string value, you will face an error called “TypeError: list indices must be integers or slices, not str”. The way to avoid encountering this error is to always assign an integer value to the variable.
Example:
# Declare a list list1 = ['Apple', 'Banana', 'Oranges'] # Declare a index variable index = '1' print('Value at List Index 1', list1[index])
Output:
Traceback (most recent call last):
File "list-error.py", line 5, in <module>
print('Value at List Index 1', list1[index])
TypeError: list indices must be integers or slices, not str
In the above example, we have declared a list with the name “list1” and an index variable to access the value of list with the name ‘index’ and given value “1” as a string, not an integer.
index = '1' # Declare index variable as string
# Inilise a list list1 = ['Apple', 'Banana', 'Oranges'] # Inilise a index variable index = 1 print('Value at List Index 1', list1[index])
Output:
Value at List Index 1 Banana