Python Practice › List Programs › Program 50

Move zeros to the end

EasyList Programs · 50 of 100

Write a Python program to move all zeros to the end of a list.

Advertisement
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

  1. Non-zero values followed by the right number of zeros.

Solution

Python
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.

More list programs

← All 100 List Programs

Leave a Comment