i want to remove all zero from one list and append all of them to another list but not all of them remove

1.3k Views Asked by At

i want to remove all zero from one list and append them to another list,but when more than one zero come after each other,one of them,does not remove.

zero=[]
l=[2,3,6,0,0,5,6,0,7]
for i in l:
    if i==0:
        l.remove(i)
        zero.append(i)
print(l)
print(zero)


l=[2, 3, 6, 5, 6, 0, 7]
zer0=[0, 0]

in this out put,one of zero,does not remove

4

There are 4 best solutions below

0
Relandom On BEST ANSWER

You are iterating through a list that you are modifying. If you remove a current element from this list, it will shrink and next(l) will skip one element. To avoid it, always iterate through a copy of the list. For example list(l) or l[:].

zero=[]
l=[2,3,6,0,0,5,6,0,7]
for i in list(l):
    if i==0:
        l.remove(i)
        zero.append(i)
print(l)
print(zero)
1
Rakesh On

Do not modify a list while iterating the object. instead you can use a copy. l[:]

Ex:

zero=[]
l=[2,3,6,0,0,5,6,0,7]
for i in l[:]:
    if i==0:
        l.remove(i)
        zero.append(i)
print(l)
print(zero)
0
Alexandre B. On

You can use non_zero from the numpy module. It has been designed to find all values different to 0.

And if you want to get all the zero, you can find them with np.where

l = [2, 3, 6, 0, 0, 5, 6, 0, 7]

import numpy as np
np_l = np.array(l)

non_zero = np_l[np.nonzero(np_l)]
print(non_zero)
# [2 3 6 5 6 7]

zero = np_l[np.where(np_l == 0)]
print(zero)
# [0 0 0]
0
Andrej Kesely On

Using itertools.groupby:

from itertools import groupby

l=[2,3,6,0,0,5,6,0,7]

non_zeros = []
zeros = []
for v, g in groupby(l, lambda k: k==0):
    if v:
        zeros.extend(g)
    else:
        non_zeros.extend(g)

print(non_zeros)
print(zeros)

Prints:

[2, 3, 6, 5, 6, 7]
[0, 0, 0]