python : list index out of range error while iteratively popping elements

Viewed 829917

I have written a simple python program

l=[1,2,3,0,0,1]
for i in range(0,len(l)):
       if l[i]==0:
           l.pop(i)

This gives me error 'list index out of range' on line if l[i]==0:

After debugging I could figure out that i is getting incremented and list is getting reduced.
However, I have loop termination condition i < len(l). Then why I am getting such error?

12 Answers

I think the best way to solve this problem is:

l = [1, 2, 3, 0, 0, 1]
while 0 in l:
    l.remove(0)

Instead of iterating over list I remove 0 until there aren't any 0 in list

I think most solutions talk here about List Comprehension, but if you'd like to perform in place deletion and keep the space complexity to O(1); The solution is:

i = 0
for j in range(len(arr)):
if (arr[j] != 0):
    arr[i] = arr[j]
    i +=1
arr = arr[:i] 
x=[]
x = [int(i) for i in input().split()]
i = 0
    while i < len(x):
        print(x[i])
        if(x[i]%5)==0:
            del x[i]
        else:
            i += 1
print(*x)

Code:

while True:
        n += 1
        try:
          DATA[n]['message']['text']
        except:
          key = DATA[n-1]['message']['text']
          break

Console :

Traceback (most recent call last):
  File "botnet.py", line 82, in <module>
    key =DATA[n-1]['message']['text']
IndexError: list index out of range

I recently had a similar problem and I found that I need to decrease the list index by one.

So instead of:

if l[i]==0:

You can try:

if l[i-1]==0:

Because the list indices start at 0 and your range will go just one above that.

Related