Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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]

Solution 2:

def removeLeadingZeros(a):
    for l in a:
        if l == 0:
            a = a[1:]
        else:
            breakreturn 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

Solution 3:

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:]
        breakprint (a)

Solution 4:

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))

Post a Comment for "Delete First Occuring Zeros From A List In Python"