12
X = [0,5,0,0,3,1,15,0,12]

for value in range(0,len(X)):

    if X[value] <= 0:
        del X[value]
        print(X)
print(X)

I run the code but then i get an error saying that the list is out of index range. Can someone please help me out on how to correct this mistake

Julien
  • 12,611
  • 4
  • 26
  • 51
Andrews
  • 129
  • 1
  • 1
  • 3

2 Answers2

29

Try a list comprehension.

X = [0,5,0,0,3,1,15,0,12]
X = [i for i in X if i != 0]
JahKnows
  • 2,480
  • 2
  • 20
  • 37
7
>>> X = [0,5,0,0,3,1,15,0,12]
>>> list(filter(lambda num: num != 0, X))
[5, 3, 1, 15, 12]
pramesh
  • 1,774
  • 1
  • 14
  • 27