Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete first occuring zeros from a list in python

Tags:

python-3.x

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.

like image 535
Watarap Avatar asked Dec 07 '25 06:12

Watarap


1 Answers

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]
like image 53
OneCricketeer Avatar answered Dec 09 '25 19:12

OneCricketeer