Move all zeroes to end of the array using List Comprehension in Python

Given a list of numbers, move all the zeroes to the end using list comprehensions. For example, the result of [1, 3, 0, 4, 0, 5, 6, 0, 7] is [1, 3, 4, 5, 6, 7, 0, 0, 0].

It's a single line code using the list comprehensions. See the following steps to achieve the result.

• Initialize the list of numbers.

• Generate non-zeroes from the list and generate zeroes from the list. Add both. And store the result in a list.

• Print the new list.

Example

# initializing a list
numbers = [1, 3, 0, 4, 0, 5, 6, 0, 7]
# moving all the zeroes to end
new_list = [num for num in numbers if num != 0] + [num for num in numbers if num == 0]
# printing the new list
print(new_list)
[1, 3, 4, 5, 6, 7, 0, 0, 0]

If you run the above code, you will get the following result.

Output

[1, 3, 4, 5, 6, 7, 0, 0, 0]

Conclusion

If you have any queries regarding the tutorial, mention them in the comment section.

Updated on: 12-Feb-2020

2K+ Views