Moving zero at the end of list is very common problem in programming. You may find the various ways to solve but today we’ll see the easiest way to solve it. So let’s begin
a=[1,3,0,5,0,4,0,3,2] b= print("old list is: ",a) for i in a: if i is 0: b.append(i) a.remove(i) print("New list is: ",a+b)
old list is: [1, 3, 0, 5, 0, 4, 0, 3, 2] New list is: [1, 3, 5, 4, 3, 2, 0, 0, 0]
As we’ve given the list A and we want to shift all zero at the end of the list. For that, we are using the empty list named list B. The list B will contain all zero which occurs in list A and at the same time we are removing the zero from list A. Thereby, In list A we have left only non-zero element and in list B only zero element. So moving all zero at the end we just need to concatenate list A with B.
Let’s Understand How Code works
We are iterate our all values of list A with for loop, so in first iteration i containing value 1. Now the control will go inside for loop and checks weather the i value is 0 or not by if statement.( we use the identity operator ” is ” if identity operator not works due to python versions or any other problem then you can also check with ” if(a == 0 )” ). As we know we’ve 1 in i variable and therefore control not goes under if statement. this loop works until the last element of the list A.
At the third iteration i variable contains zero and if statement true and the element zero will be append in list b and at the next statement zero will be remove from list A. This is how all zero will be shifted in list B and A becomes non-zero containing list.
At last we simply concatenate list A with list B to move all zero in last.
append ( ) and remove ( ) methods in list
- append () :The append is the method that used with a list object and take one argument which it will be put into the last position of the list.
- remove(): The remove method is used for removing the element from list and it takes one argument the needed to be remove. it remove the first matching element that passed as argument.