Python Program to Move All Zeros to End of List
result = [x for x in lst if x != 0] + [0] * lst.count(0).Examples
How to Think About It
Algorithm
Code
def move_zeros_to_end(lst): non_zeros = [x for x in lst if x != 0] zeros_count = lst.count(0) return non_zeros + [0] * zeros_count # Example usage lst = [0, 1, 0, 3, 12] result = move_zeros_to_end(lst) print(result)
Dry Run
Let's trace the list [0, 1, 0, 3, 12] through the code
Filter non-zero elements
non_zeros = [1, 3, 12]
Count zeros
zeros_count = 2
Combine non-zeros and zeros
result = [1, 3, 12] + [0, 0] = [1, 3, 12, 0, 0]
| Step | non_zeros | zeros_count | result |
|---|---|---|---|
| 1 | [1, 3, 12] | ||
| 2 | 2 | ||
| 3 | [1, 3, 12, 0, 0] |
Why This Works
Step 1: Extract non-zero elements
Using list comprehension, we collect all elements that are not zero to keep their original order.
Step 2: Count zeros
We use count(0) to find how many zeros are in the list.
Step 3: Combine lists
We add the zeros at the end by creating a list of zeros multiplied by their count and concatenate it with the non-zero list.
Alternative Approaches
def move_zeros_inplace(lst): pos = 0 for i in range(len(lst)): if lst[i] != 0: lst[pos], lst[i] = lst[i], lst[pos] pos += 1 return lst lst = [0, 1, 0, 3, 12] print(move_zeros_inplace(lst))
def move_zeros_filter(lst): non_zeros = list(filter(lambda x: x != 0, lst)) zeros_count = lst.count(0) non_zeros.extend([0] * zeros_count) return non_zeros lst = [0, 1, 0, 3, 12] print(move_zeros_filter(lst))
Complexity: O(n) time, O(n) space
Time Complexity
The program loops through the list once to filter non-zero elements and once to count zeros, both operations are O(n).
Space Complexity
It creates a new list for non-zero elements and zeros, so space complexity is O(n). The in-place method reduces space to O(1).
Which Approach is Fastest?
The in-place swapping method is fastest in space usage but slightly more complex; list comprehension is simpler and fast enough for most uses.
| Approach | Time | Space | Best For |
|---|---|---|---|
| List comprehension + count | O(n) | O(n) | Readability and simplicity |
| In-place swapping | O(n) | O(1) | Memory efficiency and large lists |
| Filter + extend | O(n) | O(n) | Functional style preference |