pythonindexoutofrangeexception

python at while loop IndexError: list index out of range


def solution(progresses, speeds):
    answer = []
    while len(progresses) != 0:
        count = 0
        for i in range(len(progresses)):
            if progresses[i] < 100:
                progresses[i] += speeds[i]
        while (progresses[0] >= 100) and (len(progresses) != 0):
            print("pop: ", progresses.pop(0))
            speeds.pop(0)
            count += 1
        if count != 0:
            answer.append(count)

    return answer


solution([93, 30, 55], [1, 30, 5])

my python terminal show me an error like this.

    while (progresses[0] >= 100) and (len(progresses) != 0):
IndexError: list index out of range

i dont know why this error comes up..... help me


Solution

  • As mentioned in other comments you should avoid modifying the list which is used in the while or for loop checks.


    If you want to understand why your code is failing. The problem is this line:

    while (progresses[0] >= 100) and (len(progresses) != 0):
    

    You are accessing element zero (progresses[0]) but the list is empty. If you swap the two checks, it works fine (because if the first check already returns false the second check is not performed at all).

    while (len(progresses) != 0 and progresses[0] >= 100):