20
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
  • 13,986
  • 5
  • 29
  • 53
Andrews
  • 209
  • 1
  • 2
  • 3

2 Answers2

42

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,618
  • 3
  • 22
  • 37
10
>>> X = [0,5,0,0,3,1,15,0,12]
>>> list(filter(lambda num: num != 0, X))
[5, 3, 1, 15, 12]
pramesh
  • 1,914
  • 1
  • 19
  • 30