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
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.
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.
Try a list comprehension.
X = [0,5,0,0,3,1,15,0,12]
X = [i for i in X if i != 0]
>>> X = [0,5,0,0,3,1,15,0,12]
>>> list(filter(lambda num: num != 0, X))
[5, 3, 1, 15, 12]
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