-2

I'm puzzle why the below code does not properly pop and extend the list for each zero it identifies.

def move_zeros(array):
    array.extend([array.pop(i) for i,x in enumerate(array) if x != 0 and x != False])
    return array

A similar post that I reviewed for answers: How to move zeros to the end of a list [closed]

Community
  • 1
  • 1
Nico
  • 27
  • 6

1 Answers1

3

The reason you don't get the appropriate result is because you iterate over an array and change his elements simultaneously.

This is bad practice, you should work with another list\variable in order to achieve your goal.

omri_saadon
  • 10,193
  • 7
  • 33
  • 58