+ 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

27th Jul 2020, 3:34 PM
Kirill
Kirill - avatar
9 Respuestas
+ 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.
27th Jul 2020, 4:11 PM
XXX
XXX - avatar
+ 2
We have two problems: 1. False == 0 2. The list is updated while looping
27th Jul 2020, 3:59 PM
Ali Abdelhady
Ali Abdelhady - avatar
+ 2
XXX i see
27th Jul 2020, 4:55 PM
Kirill
Kirill - avatar
+ 1
Ali Abdelhady how do we fix them?
27th Jul 2020, 4:01 PM
Kirill
Kirill - avatar
+ 1
XXX thanks
27th Jul 2020, 4:17 PM
Kirill
Kirill - avatar
+ 1
XXX why is it bad to change the list while looping over it?
27th Jul 2020, 4:20 PM
Kirill
Kirill - avatar
+ 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
27th Jul 2020, 4:51 PM
XXX
XXX - avatar
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
27th Jul 2020, 4:08 PM
Ali Abdelhady
Ali Abdelhady - avatar
0
false is Boolean
29th Jul 2020, 10:31 AM
Tanisha Biswas
Tanisha Biswas - avatar