yungstirjoey666
yungstirjoey666

Reputation: 21

Move all zeroes to the end of a list

Basically the code is asking me to move all zeroes towards the end of the list. Here is my code so far:

def moveZerosToEnd(l):
  for i in l:
    #look for zeros
    if int(i) == 0:
      j = nz(l,i)
      #swap zero with nonzero
      l[i], l[j] =  l[j], l[i]
  return l
    
def nz(l,i):
  #look for nonzero
  while i < len(l) and l[i] == 0:
    #progress if zero
    i += 1
  #return nonzero value
  return i
            


l = []
for i in range(5): l.append(int(input()))
moveZerosToEnd(l)
print(l)

However, whenever I type in five numbers, it just results in the same list unaltered. I am wondering what I did wrong here and how to fix it.

Upvotes: 0

Views: 1422

Answers (3)

Daniel Hao
Daniel Hao

Reputation: 4980

Why bother all hassle? The simplest approach for this move_zeros to the end is one-liner to use the tricks of True or False in the sorted key (lambda):

It's to return the same list (in-place sort), but if you need a new list, you can do so easily.

A = [5,4, 0,3, 0, 2,1,0,-1,-2]
A.sort(key=lambda x: x == 0 )    # trick:  test item if is zero, "True"
                                 # all non-zero num. are "False" 
                                 # all False comes before Truth

# Or this:
A[:] = sorted(A, key=lambda x: x == 0)
[5, 4, 3, 2, 1, -1, -2, 0, 0, 0]

Upvotes: 0

Tanner Stratford
Tanner Stratford

Reputation: 152

You could also use remove() and append()

def moveZerosToEnd(l):
    for i in l:
    #look for zeros
        if(i == 0):
            l.remove(i)
            l.append(i)
    return l

l = []
for i in range(5): l.append(int(input("What is the number: ")))
moveZerosToEnd(l)
print(l)

Upvotes: 0

Buddy Bob
Buddy Bob

Reputation: 5889

Try this homemade example.

  • retrieve all the elements in your list that are not "0" and create a new list out of this
  • extend every occurance of "0" into this new list
    your_list = [5,4,3,2,1,0,0,0,-1,-2]
    new_list = [i for i in your_list if i != 0]
    new_list.extend([0]*your_list.count(0))
    

    output

    [5, 4, 3, 2, 1, -1, -2, 0, 0, 0]
    

    Upvotes: 1

  • Related Questions