

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- Move all zeroes to end of array in C++
- Move Zeroes in Python
- Moving all zeroes present in the array to the end in JavaScript
- In-place Move Zeros to End of List in Python
- Python List Comprehension?
- How to move all the zeros to the end of the array from the given array of integer numbers using C#?
- Count set bits using Python List comprehension
- Nested list comprehension in python
- In-place Algorithm to Move Zeros to End of List in JavaScript
- Python List Comprehension and Slicing?
- Move first element to end of a given Linked List in C++
- Move all zeros to start and ones to end in an Array of random integers in C++
- Move all zeros to the front of the linked list in C++
- List comprehension and ord() in Python to remove all characters other than alphabets
- How to move the pointer of a ResultSet to the end of the table using JDBC?
Advertisements