Exercise 85

Write a python program which that move the null values of a list to the end of the list while keeping the order of the other non-null elements. Example if the list is: L = [7, 0, 11, 5, 0, 21, 0, 2, 0, 0, 9]the output is: [7, 11, 5, 21, 2, 9, 0, 0, 0, 0, 0]

Solution

L = [7 , 0 , 11 , 5 , 0 , 21 , 0 , 2 , 0 , 0 , 9]
L_rearranged = []
# Extract the list of non-zero elements from L and the list of zero elements
L_nuls = []
L_non_nuls = []

for x in L:
if x == 0:
L_nuls.append(x)
else:
L_non_nuls.append(x)

# on additionne les deux listes
L_rearranged = L_non_nuls + L_nuls

print(L_rearranged)
Younes Derfoufi
my-courses.net

Leave a Reply