What is the problem?
You are removing elements from the list, using list.pop while iterating but you haven't considered the fact that the elements from the list(with a bigger index) have changed index.
How can you approach the solution?
Staying consistent with your code, it would be necessary to subtract the total of elements removed before using the list.pop method.
NOTE: On the function, I put a print function for printing the elements; this is only for debugging purpouses and should be removed in the final code
Code
Here is the code; as stated in the comments, the function is returning None and it's modifying the list in-place.
Also, I converted the for loop at the end, from
for i in range(0,c):
lst.append(0)
to this code, using generator expression, combined with the list.extend method:
lst.extend(0 for _ in range(c))
Here is the code implementation that i came up with:
def move_zero(lst):
"""
Given a list of integers, moves all non-zero numbers to the beginning of the list and
moves all zeros to the end of the list. This function returns nothing and changes the given list itself.
For example:
- After calling move_zero([0,1,0,2,0,3,0,4]), the given list should be [1,2,3,4,0,0,0,0] and the function returns nothing
- After calling move_zero([0,1,2,0,1]), the given list should be [1,2,1,0,0] and the function returns nothing
- After calling move_zero([1,2,3,4,5,6,7,8]), the given list should be [1,2,3,4,5,6,7,8] and the function returns nothing
- After calling move_zero([]), the given list should be [] and the function returns nothing
"""
c = 0
for i in range (0,len(lst),1):
if not lst[i-c]:
lst.pop(i-c)
c += 1
lst.extend(0 for _ in range(c))
print(lst)
move_zero([1,2,0,3,0])
I would also suggest to iterate over a copy of the list:
def move_zero(lst):
"""
Given a list of integers, moves all non-zero numbers to the beginning of the list and
moves all zeros to the end of the list. This function returns nothing and changes the given list itself.
For example:
- After calling move_zero([0,1,0,2,0,3,0,4]), the given list should be [1,2,3,4,0,0,0,0] and the function returns nothing
- After calling move_zero([0,1,2,0,1]), the given list should be [1,2,1,0,0] and the function returns nothing
- After calling move_zero([1,2,3,4,5,6,7,8]), the given list should be [1,2,3,4,5,6,7,8] and the function returns nothing
- After calling move_zero([]), the given list should be [] and the function returns nothing
"""
c = 0
for i,x in enumerate(lst.copy()):
if not x:
lst.pop(i-c)
c += 1
lst.extend(0 for _ in range(c))
print(lst)
move_zero([1,2,0,3,0])
Output:
[1,2,3,0,0]