
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
- Related Articles
- Move all zeroes to end of array in C++
- Move All the Zeros to the End of Array in Java
- In-place Move Zeros to End of List in Python
- Moving all zeroes present in the array to the end in JavaScript
- Python List Comprehension?
- How to move all the zeros to the end of the array from the given array of integer numbers using C#?
- Move Zeroes in Python
- Count set bits using Python List comprehension
- Nested list comprehension in python
- List comprehension and ord() in Python to remove all characters other than alphabets
- Python List Comprehension and Slicing?
- K’th Non-repeating Character in Python using List Comprehension and OrderedDict
- Move all zeros to start and ones to end in an Array of random integers in C++
- In-place Algorithm to Move Zeros to End of List in JavaScript
- Python Program to move numbers to the end of the string

Advertisements