Reputation: 7519
The following code returns an error on line 6 of type : TypeError: 'NoneType' object is not subscriptable
What is wrong?
def insertAtList(name, score, H):
E = [score, name]
i = len(H) - 1
if H[i] != None:
print("fail")
while H[i-1][0] < E[0] or H[i-1] == None:
H[i] = H[i-1]
i -= 1
H[i] = E
for c in range (0,len(H) - 1):
print(H[c])
def testq4():
H = [[940, "Mike"], [880, "Rob"], [830, "Jill"], [790, "Paul"],
[750, "Anna"], [660, "Rose"], [650, "Jack"], None, None, None]
insertAtList("Mark",675,H)
testq4()
Upvotes: 0
Views: 87
Reputation: 6395
The error message is pretty clear. You are accessing a None-value, trying to treat it as a list. And the reason for that is that you first try & access it that way before you test if it is None. So you need to revert your conditions in the while-loop. On top of that, checking for None is not done using the != or == operator, but the "is" and "is not" operator, because None is a singleton. Last but not least, you should consider to replace your code with something that leverages the builtin capabilities of list-sorting:
def insertAtList(name, score, highscores):
highscores.append([score, name])
highscores.sort(key=lambda entry: 0 if entry is None else entry, reverse=True)
H = [[940, "Mike"], [880, "Rob"], [830, "Jill"], [790, "Paul"],
[750, "Anna"], [660, "Rose"], [650, "Jack"], None, None, None]
insertAtList("Mark",675,H)
print H
Upvotes: 1
Reputation: 4134
You need to swap the order of the operands in your while-loop condition. The or
checks the conditions from left to right, and stops evaluating when it has found one True
value. That's what you'll want to do when you find out that H[i-1]
is None
. Currently, if H[i-1]
is None
, you're still trying to evaluate H[i-1][0]
, which does not exist.
Try it like this:
# ...
if H[i] is not None:
print("fail")
while H[i-1] is None or H[i-1][0] < E[0]:
H[i] = H[i-1]
i -= 1
# ...
Upvotes: 2