I want to just move the zero’s to left and don’t want to sort the list.
For example, if my list is like:
nums = [1, 10, 20, 0, 59, 63, 0, 8, 0]
Here’s the output which I desire after moving all the Zero’s to left:
output = [0, 0, 0, 1, 10, 20, 59, 63, 8]
Here’s the code I tried:
class Solution: def moveZeroes(self, nums): c = 0 for i in range(len(nums)): if nums[i] != 0: nums[i], nums[c] = nums[c], nums[i] c += 1 return nums print(Solution().moveZeroes(nums))
This code gives me output as:
[1, 10, 20, 59, 63, 8, 0, 0, 0]
But my desired output is:
[0, 0, 0, 1, 10, 20, 59, 63, 8]
Advertisement
Answer
output = [] for i in nums: if i == 0: output.insert(0, 0) else: output.append(i) output