I am somewhat of a beginner and just took up leetcode problems. The question asks to write a function to remove all zeroes from a list, and to add them at the end without disturbing the order of the other digits
my approach was to count the total zeroes and remove them. and adding those zeroes at the end.
def moveZeroes(nums):
zeroCount = 0
for i in nums:
if i==0:
nums.remove(i) #STATEMENT1
zeroCount+=1
while zeroCount>0:
nums.append(0)
zeroCount-=1
print(nums)
this code works for most inputs. one input that this code does not work with is [0, 0, 1]. zeroCount ends up being 1, and the final print statement prints out [0, 1, 0], ie. it is ignoring the second 0 in the list. if I remove #STATEMENT1 (nuts.remove(i), then zeroCount gives the correct count of 2.
however even after adding a separate for loop to remove all the zeroes, it still ignores the second zero ie. the list becomes [0, 1].
I am not able to understand why this is happening. can anyone explain the reason behind this?
Neil Laturkar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.