0

I need to count again whenever there is a bigger number on the list. But I don't know how to deal with the IndexError and why it happened.

    for i in range(len(left_days)):
        largest = left_days[0]
        count = 1
        del left_days[0]

        if(left_days[i]<=largest):
            count+= 1
            del left_days[i]
            if i == len(left_days)-1:
                answer.append(count)
            i = 0

        else left_days[i]>largest:
            answer.append(count)

This is the error.

 File "/solution_test.py", line 18, in test
   actual0 = solution(p0_0,p0_1)
 File "/solution.py", line 24, in solution
   if(left_days[i]<=largest):
IndexError: list index out of range```
  • 3
    If you keep deleting items from `left_days`, your list gets shorter, so `i` will run past the end. `i` is iterating the initial length of the list, before you started shortening it. Whatever you were trying to do, this is not the way to do it. – khelwood Nov 12 '19 at 15:01
  • Also he tries to reset i to zero which has no effect – Lee Nov 12 '19 at 15:07

2 Answers2

2

The issue is that you iterate over the length of the list, but at the same time you delete items of it. At some point, your iterator will be greater than your list length. So an IndexError occurs.

As an example, look at this:

x = [0,1,2,3,4,5,6,7,8,9]

for i in range(len(x)):
    del x[i]
    print(i, x)

# Out:   
0 [1, 2, 3, 4, 5, 6, 7, 8, 9]
1 [1, 3, 4, 5, 6, 7, 8, 9]
2 [1, 3, 5, 6, 7, 8, 9]
3 [1, 3, 5, 7, 8, 9]
4 [1, 3, 5, 7, 9]

IndexError: list assignment index out of range

An IndexError occurred since i is 5 now, but your list only has 5 elements left. Since Python starts iterating at 0, you are trying to delete the 6th element, which does not exist.

Ben Soyka
  • 816
  • 10
  • 25
Nils
  • 910
  • 8
  • 30
0

As a general rule it is a very bad practice to modify the thing you are iterating, especially if you are deleting its contents (there are far too many examples in SO on this issue to list).

Always, you either iterate in a copy of the list to modify the original, or iterate the original creating/modifying a copy:

left_days_1 = list(left_days)
for i in range(len(left_days_1)):
    largest = left_days[0]
    count = 1
    del left_days[0]

    if(left_days_1[i]<=largest):
        count+= 1
        del left_days[i]
        if i == len(left_days)-1:
            answer.append(count)
        i = 0

    elif left_days_1[i]>largest:
        answer.append(count)
Tarifazo
  • 4,118
  • 1
  • 9
  • 22