Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (47.6k points)

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 the list is getting reduced.

However, I have loop termination condition i < len(l). Then why I am getting such error?

2 Answers

0 votes
by (106k points)
edited by

This error is because you are reducing the length of your list l as you iterate over it, so as you approach the end of your indices in the range statement, some of those indices are no longer valid.

I think you want to do is:

l = [x for x in l if x != 0]

This will return a copy of l without any of the elements that were zero. You could even shorten that last part to just if x, since non-zero numbers evaluate to True.

You can write the fresh code as follows:

i = 0 

while i < len(l): 

  if l[i] == 0: 

     l.pop(i) 

  else: 

     i += 1

To know more about this you can have a look at the following video tutorial:-

0 votes
by (20.3k points)

Here, the expression len(l) is evaluated only one time, at the moment the range() builtin is evaluated. The range object constructed at that time does not change; it can't possibly know anything about the object l.

Related questions

+1 vote
2 answers
asked Aug 28, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...