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?
So, how can you fix the code? Python tells you in which line and on which list the error occurs. To pin down the exact problem, check the value of the index just before the error occurs. To achieve this, you can print the index that causes the error before you use it on the list.
But in case you mention an index in your code that is outside the range of the list, you will encounter an IndexError. “List index out of range” error occurs in Python when we try to access an undefined element from the list. The only way to avoid this error is to mention the indexes of list elements properly.
To solve the “index error: list index out of range” error, you should make sure that you're not trying to access a non-existent item in a list. If you are using a loop to access an item, make sure that the loop accounts for the fact that lists are indexed from zero.
Using the wrong value in the range() function in a Python for loop. You'll get the Indexerror: list index out of range error when iterating through a list and trying to access an item that doesn't exist. One common instance where this can occur is when you use the wrong integer in Python's range() function.
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.
It looks like what you want to do is:
l = [x for x in l if x != 0]
which will return a copy of l
without any of the elements that were zero (that operation is called a list comprehension, by the way). You could even shorten that last part to just if x
, since non-zero numbers evaluate to True
.
There is no such thing as a loop termination condition of i < len(l)
, in the way you've written the code, because len(l)
is precalculated before the loop, not re-evaluated on each iteration. You could write it in such a way, however:
i = 0 while i < len(l): if l[i] == 0: l.pop(i) else: i += 1
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
.
P.S. l
is a lousy name for a value! It looks like the numeral 1, or the capital letter I.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With