
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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.
Advertisements