
- 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 Zeroes in Python
Suppose we have an array to hold some numbers. There are non-zero values as well as zero values. So we have to send all zeros to the right without changing the relative order of other numbers. So if the array is like [0, 1, 5, 0, 3, 8, 0, 0, 9], then the final array will be [1, 5, 3, 8, 9, 0, 0, 0, 0]
To solve this, we will follow these steps −
- Suppose index = 0
- for i = 0 to the length of A
- if A[i] != 0, then
- A[index] := A[i]
- index := index + 1
- if A[i] != 0, then
- for i = index to the length of A
- A[i] = 0
Example
Let us see the following implementation to get a better understanding −
class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ insert_index = 0 for i in range(len(nums)): if nums[i] != 0: nums[insert_index]=nums[i] insert_index+=1 for i in range(insert_index,len(nums)): nums[i]=0 nums = [0,1,5,0,3,8,0,0,9] ob1 = Solution() ob1.moveZeroes(nums) print(nums)
Input
nums = [0,1,5,0,3,8,0,0,9]
Output
[1,5,3,8,9,0,0,0,0]
- Related Articles
- Move all zeroes to end of the array using List Comprehension in Python
- Move all zeroes to end of array in C++
- Set Matrix Zeroes in Python
- In-place Move Zeros to End of List in Python
- Python Program to Count trailing zeroes in factorial of a number
- Python - Move a column to the first position in Pandas DataFrame?
- Check if a king can move a valid move or not when N nights are there in a modified chessboard in Python
- Factorial Trailing Zeroes in C++
- Ones and Zeroes in C++
- Python program to move spaces to front of string in single traversal
- Python Pandas BusinessHour offset object - Move to the next business day
- Python Pandas CustomBusinessHour offset object - Move to the next business day
- Python Program to move numbers to the end of the string
- Python code to move spaces to the front of string in a single traversal
- Program to find lexicographically smallest string to move from start to destination in Python

Advertisements