Python Program to Move All Zeros to the End of a List
Intermediate · Lists
This program moves every 0 in a list to the end while keeping the other numbers in their original order, so [0, 4, 0, 7] becomes [4, 7, 0, 0]. It works in place, inside the same list, which is how the question is usually asked in coding interviews.
Program
Original list: [0, 4, 0, 7, 2, 0, 9, 3] Zeros moved to the end: [4, 7, 2, 9, 3, 0, 0, 0]
How it works
positionmarks the next free spot at the front for a non-zero number, starting at index 0.- Each time the loop finds a non-zero number, it swaps it into
positionand movespositionone step on. - The zeros get swapped backwards as the non-zero numbers move forwards, so they all end up at the end.
- Non-zero numbers are placed in the order they are found, so 4, 7, 2, 9 and 3 keep their order.
- The list is scanned only once and no second list is needed.
Other ways to write it
Building a new list
Zeros moved to the end: [4, 7, 2, 9, 3, 0, 0, 0]
Collect the non-zero numbers, then add as many zeros as were left out. It is easy to follow, but it makes new lists instead of changing the original.
Using sort() with a key
Zeros moved to the end: [4, 7, 2, 9, 3, 0, 0, 0]
The key turns each number into False or True, and because Python sorts stably, the non-zero numbers keep their order.
Try it yourself
Change the program to move all zeros to the front instead.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises