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.
Python code
12 linesdef 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
[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
- Using `nums.sort(key=bool, reverse=True)` but that's not in-place stable for all cases
- 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
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.