Member-only story
Python Coding Question #3
Move Zeros To End Of List
Let’s see the 3rd coding challenge!!!!!!!!!!!!!!!!!!!!!!!!!!!
Question:
Given a list of numbers with zeros in between, write a python program to move the zeros to end of the list maintaining the original order of non-zero elements.
Let’s see the solutions:
- Using list operations remove and append inside the for loop
def move_zeros_end_of_list(num_list):
for num in num_list:
if num == 0:
num_list.remove(0)
num_list.append(0)
return num_list
num_list = [1,4,23,0,9,0,8,0,12]
print(move_zeros_end_of_list(num_list))
# Ouput - [1, 4, 23, 9, 8, 12, 0, 0, 0]In this solution, you can see that even though we are getting the expected results one issue is that the original list is being modified, so in order to avoid that use the copy() method to keep the original list same, so lets see the modified code:
def move_zeros_end_of_list(num_list):
for num in num_list:
if num == 0:
num_list.remove(0)
num_list.append(0)
return num_list
num_list = [1,4,23,0,9,0,8,0,12]
result_list = move_zeros_end_of_list(num_list.copy())
print('Result is:',result_list)
print('Original list is:', num_list)
# Result list is: [1…







