Watarap
Watarap

Reputation: 307

Delete first occuring zeros from a list in python

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.

Upvotes: 3

Views: 2136

Answers (4)

Edwin van Mierlo
Edwin van Mierlo

Reputation: 2488

slightly different then answers already given, so here goes:

a = [0,0,0,0,0,0,0,0,3,4,0,6,0,14,16,18,0]

for i in range(0, len(a)):
    if a[i] != 0:
        a = a[i:]
        break

print (a)

Upvotes: 2

skrx
skrx

Reputation: 20438

itertools.dropwhile drops elements of the iterable as long as the predicate is true:

from itertools import dropwhile

a = list(dropwhile(lambda x: x==0, a))

Upvotes: 3

Yorian
Yorian

Reputation: 2062

def removeLeadingZeros(a):
    for l in a:
        if l == 0:
            a = a[1:]
        else:
            break
    return a

or if you want it as a oneliner using numpy arrays:

a = list(a[np.where(np.array(a) != 0)[0][0]:]) # you could remove the list() if you don't mind using numpy arrays

Upvotes: 2

OneCricketeer
OneCricketeer

Reputation: 191738

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]

Upvotes: 9

Related Questions