Sunraj Patel
Sunraj Patel

Reputation: 5

IndexError: list index out of range even though printing individual lists and index doesn't seem to have an error

take = randint(0, len(teacherClass[teacher])-1)
print(take)
print(teacherClass)
print(teacher)
print(teacherClass[teacher])
triesDone = 0
while triesDone < len(teacherClass[teacher]):
    cp = teacherClass[teacher][take]
    if (cp not in (blocks[teacher][day])) and (blocksS[cp][day][block] == ""):
        blocks[teacher][day][block] = cp
        blocksS[cp][day][block] = teacherSub[teacher]
    take +=1
    triesDone += 1
    if take == len(teacherClass[teacher])-1:
        take = 0

When I run the program after some time, the above part is hit and the program starts working as intended but line 8 raises the error ("IndexError: list index out of range").

Trying to solve that and understand the problem, I tried to print the entire dictionary(teacherClass) and the indices used(teacher and take) but even after that, it seems the line 8 should work. Output I am getting: Output with list and index

Please help me understand the problem and a solution. Thanks

Upvotes: 0

Views: 85

Answers (1)

quamrana
quamrana

Reputation: 39374

There is a possibility that take could be: len(teacherClass[teacher])-1 from the assignment on the first line. Later there is take += 1. This mean that it is larger than the limit, so take = 0 is never executed.

Did you mean:

if take >= len(teacherClass[teacher])-1:
    take = 0

Upvotes: 1

Related Questions