Two different results

Question:

The below code provides the results I want (move the number to the front and 0 to the end of the list) on programminghero’s playground. When I put it in a jupyter notebook the result is all 0’s.
So, move_zero([0,1,0,2,0,3,0,5]) should return [1,2,3,5,0,0,0,0] but in jupyter it returns [0,0,0,0,0,0,0,0].

def move_zero(lst):

    new_list = lst
    counter = 0
    for each in new_list:
        if each == 0:
            new_list.pop(counter)
            new_list.append(0)
            counter -= 1
        counter += 1
    return new_list
        
print(move_zero([0,1,0,2,0,3,0,5]))
Asked By: jpaineh

||

Answers:

redacted — code had bug, not sure why it was accepted lol

Answered By: Ajay Sachdev

It is recommended that you avoid modifying a list while iterating over the list. It is usually better to construct a new list:

def move_zero(lst):
    non_zeros, zeros = [], []
    for x in lst:
        if x == 0:
            zeros.append(x)
        else:
            non_zeros.append(x)
    return non_zeros + zeros

print(move_zero([0,1,0,2,0,3,0,5])) # [1, 2, 3, 5, 0, 0, 0, 0]

Or maybe slightly less efficient but more concise:

def move_zero(lst):
    return [x for x in lst if x] + [x for x in lst if not x]
Answered By: j1-lee
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.