+ 1
Differentiate between False and 0
def move_zeros(array): for num in array: if num == 0: array.remove(num) array.append(num) return array print(move_zeros([0,1,None,2,False,1,0])) should output = [1,None,2,False,1,0,0] but instead I get = [1, None, 2, 1, 0, False, False] I tried a lot of things like checking the type or using isinstance(). I also tried doing if num != False, but then other zeros dont get pushed to the end. Please help to fix this problem
9 Réponses
+ 1
Kirill Vidov just like Ali Abdelhady said, you are looping over a list while changing it. Just take some time and go through each iteration and think about what is happening and you'll know the problem.
Instead if you make a new list, the should work just fine. But then again, False == 0 returns true, so even False is moved to the end. So you have to add another condition to it. See this
https://code.sololearn.com/cVPsPg2lJxcS/?ref=app
The first function simply makes a new list, while the second function checks for false.
+ 2
We have two problems:
1. False == 0
2. The list is updated while looping
+ 2
XXX i see
+ 1
Ali Abdelhady how do we fix them?
+ 1
XXX thanks
+ 1
XXX why is it bad to change the list while looping over it?
+ 1
Kirill Vidov for obvious reasons, when you make changes to a list while iterating on it, the loop will be affected. See this code for instance. When you are looping over the list while appending an item at its end, it results in an infinite loop because the loop never reaches the end of the list
https://code.sololearn.com/cimB0FTpNex4/?ref=app
0
Kirill Vidov On trying to make a copy of the list and specifying that the type of num should be int, False is somehow converted to 0
That leaves problem 1 unsolved...
Edit: The problem is that .remove removes the first occurrence of a 0, and False is also a 0
https://code.sololearn.com/cFf3uR01u8x9/?ref=app
0
false is Boolean