Sitemap
Python’s Gurus

Python’s Gurus is a Journal, composed by high skilled and knowledgeable Writers from Computer Science World. We’re Devs, Masters, PhDs and Experts in our domaines, possessing deep understanding and proficiency in Python & Several Techs. Sharing real solution for real problems.

Member-only story

Python Coding Question #3

--

Move Zeros To End Of List

Let’s see the 3rd coding challenge!!!!!!!!!!!!!!!!!!!!!!!!!!!

Press enter or click to view image in full size
Photo by Towfiqu barbhuiya on Unsplash

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:

  1. 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…

--

--