Editor

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

move_zeros_to_end.py
numbers = [0, 4, 0, 7, 2, 0, 9, 3]
print("Original list:", numbers)
# position is where the next non-zero number should go
position = 0
for i in range(len(numbers)):
if numbers[i] != 0:
numbers[position], numbers[i] = numbers[i], numbers[position]
position += 1
print("Zeros moved to the end:", numbers)
Output
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

  1. position marks the next free spot at the front for a non-zero number, starting at index 0.
  2. Each time the loop finds a non-zero number, it swaps it into position and moves position one step on.
  3. The zeros get swapped backwards as the non-zero numbers move forwards, so they all end up at the end.
  4. Non-zero numbers are placed in the order they are found, so 4, 7, 2, 9 and 3 keep their order.
  5. The list is scanned only once and no second list is needed.

Other ways to write it

Building a new list

Building a new list
numbers = [0, 4, 0, 7, 2, 0, 9, 3]
non_zeros = [n for n in numbers if n != 0]
zeros = [0] * (len(numbers) - len(non_zeros))
print("Zeros moved to the end:", non_zeros + zeros)
Output
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

Using sort() with a key
numbers = [0, 4, 0, 7, 2, 0, 9, 3]
# False (not zero) sorts before True (zero)
numbers.sort(key=lambda n: n == 0)
print("Zeros moved to the end:", numbers)
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises