IndexError: list index out of range while removing elements from a list Python


I'm trying to delete the zero's in my list and print only the non zero numbers in the list.

I tried the below way

l=[41,24,0,0,89]
for i in range(0,len(l)):
      if l[i]==0:
          l.pop(i)
print(l) 

But it is showing an error as

Traceback (most recent call last):
  File "HelloWorld.py", line 3, in <module>
    if l[i]==0:
IndexError: list index out of range

How can I fix this error?

1 Answer

4 years ago by

Instead of using a for loop, you can simply use membership operator to check if the element is zero

l = [41,23,0,0,89]

while 0 in l:
  l.remove(0)
print(l)

Check Output here

4 years ago by Divya