0

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]))
Random Davis
  • 6,662
  • 4
  • 14
  • 24
jpaineh
  • 3
  • 1
  • 2
    It seems like debugging this would be trivial if you put print statements on each line or stepped through it in a debugger - have you not taken such basic debugging steps yet? – Random Davis Jul 21 '22 at 20:18
  • 2
    This code will not not return your expected output anywhere it's not just Jupyter. – fynmnx Jul 21 '22 at 20:20
  • 1
    You shouldn't modify a list whilst iterating over it, it could lead to undefined behaviour. If you're running two different versions of Python this could explain the difference. Also, `new_list` is `lst`, not a new list. – Peter Wood Jul 21 '22 at 20:23
  • 1
    That playground is some weird JavaScript fake-Python thing, not normal Python. I've encountered it before in another question. Don't use it. – Kelly Bundy Jul 21 '22 at 20:54
  • 1
    @fynmnx It does in that playground. [Try it yourself](https://www.programming-hero.com/code-playground/python/index.html). – Kelly Bundy Jul 21 '22 at 20:57

2 Answers2

1

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]
j1-lee
  • 13,764
  • 3
  • 14
  • 26
-1

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

  • That still modifies a list while iterating over it, which isn't ideal: https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it – slothrop Jul 21 '22 at 20:27
  • While not ideal, there's no list indices involved so it should always work. – Ajay Sachdev Jul 21 '22 at 20:28
  • Not always. With input `[1,0,0,2,0,3,4,5]` the result is `[1,2,0,3,4,5,0,0]`. – slothrop Jul 21 '22 at 20:32