I am trying to solve a problem in which I have to remove the zeroes (both 0
and 0.0
) from a list and add them to the end of the list (the zero that is appended can be a 0
, doesn't have to be 0.0
). But the catch is that I must not remove False
. I thought I finally figured out my problem by using is
instead of ==
but for some reason it's not working:
arr = [9,0.0,0,9,1,2,0,1,0,1,0.0,3,0,1,9,0,0,0,0,9]
def move_zeros(array):
temp = array.copy()
j = 0
for p, i in enumerate(array):
if i is 0 or i is 0.0:
del temp[p - j]
j += 1
temp.append(0)
return temp
print(move_zeros(arr))
I've tried putting parentheses at the if
statement but the result is the same. It removes all the 0
but for some reason it won't remove 0.0
. Result:
[9, 0.0, 9, 1, 2, 1, 1, 0.0, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0]
I rewrote the function but outside of the function and for some reason it works:
array = [1, 0, 2, False, 0.0, 4]
for p, i in enumerate(array):
if i is 0 or i is 0.0:
del temp[p - j]
j += 1
temp.append(0)
And here the result is how I would expect it:
[1, 2, False, 4, 0, 0]
Why is the floating point zero being removed when executed outside of the function, but when the function move_zeros
is called, the floating points are not recognized in the if
statement?