Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python. How to remove zeroes from a list in Python [duplicate]

Tags:

python

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

like image 763
Andrews Avatar asked Apr 23 '18 05:04

Andrews


People also ask

How do you get rid of zeros in Python?

The lstrip() method to remove leading zeros When used, it automatically removes leading zeros ( only ) from the string. Note that this works for numbers and all characters accepted as a string. However, another method strip() will remove the leading and ending characters from the string. Python lstrip() docs.

How do I remove all instances of an item in a list Python?

Python3. Method 3 : Using remove() In this method, we iterate through each item in the list, and when we find a match for the item to be removed, we will call remove() function on the list.


2 Answers

Try a list comprehension.

X = [0,5,0,0,3,1,15,0,12]
X = [i for i in X if i != 0]
like image 172
JahKnows Avatar answered Oct 06 '22 18:10

JahKnows


>>> X = [0,5,0,0,3,1,15,0,12]
>>> list(filter(lambda num: num != 0, X))
[5, 3, 1, 15, 12]
like image 30
pramesh Avatar answered Oct 06 '22 16:10

pramesh