Move All Zeroes to End of Array using List Comprehension in Python
We will solve this problem in python using List Comprehension in a single line of code. This allows us to create a new list by iterating over an existing list in a concise and efficient manner. We can utilize list comprehension to separate the non-zero elements and zeros, then combine them together to achieve the desired result.
We have existing solution for this problem please refer Move all zeroes to end of array.
For example, consider the array [0, 1, 9, 0, 5, 0, 4]. The goal is to move all the zeroes to the end of the array, while keeping the order of the non-zero elements intact. The result of this operation would be [1, 9, 5, 4, 0, 0, 0], where the zeroes are shifted to the end and the relative order of 1, 9, 5, 4 is preserved.
li = [1, 2, 0, 4, 3, 0, 5, 0]
# to get non-zero elements first and then append zeros
li = [nonZero for nonZero in li if nonZero != 0] + [zero for zero in li if zero == 0]
print(li)
Output
[1, 2, 4, 3, 5, 0, 0, 0]
Explanation:
[nonZero for nonZero in arr if nonZero != 0]
[zero for zero in arr if zero == 0]
collects all zeros from li .- + operator concatenates these two lists, resulting in non-zero elements followed by zeros.