Python Practice › List Programs › Program 50
Move zeros to the end
Write a Python program to move all zeros to the end of a list.
Input
[3, 4, 0, 0, 0, 0, 6, 0, 4, 0, 22, 0, 0, 3, 21, 0]
Output
[3, 4, 6, 4, 22, 3, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Approach
- Non-zero values followed by the right number of zeros.
Solution
numbers = [3, 4, 0, 0, 0, 0, 6, 0, 4, 0, 22, 0, 0, 3, 21, 0]non_zero = [n for n in numbers if n != 0]print(non_zero + [0] * (len(numbers) - len(non_zero)))Output
[3, 4, 6, 4, 22, 3, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Line by line
Line 3
[0] * k makes a list of k zeros.
Learn the concept
New to this topic? Read the lesson, then come back.