I want to delete list of zeros occurring initially from the list, but it behaves oddly by the method i tried.
a = [0,0,0,0,0,0,0,0,3,4,0,6,0,14,16,18,0]
for i in a:
if i == 0: a.remove(i)
else: pass
print (a)
>>> [0, 3, 4, 0, 6, 0, 14, 16, 18, 0]
but I need an OUTPUT like this
[3, 4, 0, 6, 0, 14, 16, 18, 0]
And also lets assume the list grows or reduces so I cant keep the range of zeros and delete them. Where am I going wrong.
Your loop skips items. You remove one, then you iterate to the next position.
Just find the position of the first non-zero and trim the list
a = [0,0,0,0,0,0,0,0,3,4,0,6,0,14,16,18,0]
i = 0
while a[i] == 0:
i+=1
print(a[i:]) # [3, 4, 0, 6, 0, 14, 16, 18, 0]
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