Move Zeroes to End in Python Maintaining Order

In-place algorithm that moves all zeroes to the end of a list while preserving the relative order of non-zero elements.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 14 views 0 copies

Python code

12 lines
Python 3.9+
def move_zeroes(nums):
    non_zero_index = 0
    for i in range(len(nums)):
        if nums[i] != 0:
            nums[non_zero_index], nums[i] = nums[i], nums[non_zero_index]
            non_zero_index += 1
    return nums

if __name__ == "__main__":
    example = [0, 1, 0, 3, 12]
    result = move_zeroes(example)
    print(result)

Output

stdout
[1, 3, 12, 0, 0]

How it works

The function uses a non_zero_index pointer to track where the next non-zero element should go. When a non-zero is found at position i, it swaps with the element at non_zero_index and advances the pointer. This ensures non-zero elements keep their original order while zeroes get pushed to the end. The algorithm is O(n) time and O(1) extra space.

Common mistakes

  • Forgetting to swap correctly and overwriting values
  • Returning a new list instead of modifying in place
  • Not handling empty lists or lists with no zeroes

Variations

  1. Using `nums.sort(key=bool, reverse=True)` but that's not in-place stable for all cases
  2. Building a new list with comprehension then copying back

Real-world use cases

  • Compacting sparse arrays in data preprocessing before ML model training.
  • Shifting zero-valued entries to the end of a log buffer for faster scanning.
  • Reordering database query results to reduce zero-noise in reporting tables.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.