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