I have this question where I need to put every 0 or 0.0 at the back of the list while saving the order of the other elements, for example:
move_zero([1,3,4,[],False,None,0,0,3,0.0,4])
Will output:
[1,3,4,[],False,None,3,4,0,0,0]
Note that the function turned especially 0.0 to 0 and it's fine, this is what it should do
Now, this is my go at this question:
def move_zeros(array):
new_arr = []
count_zero = 0
for x in array:
if (x is 0) or (x is 0.0):
count_zero += 1
else:
new_arr.append(x)
return new_arr + count_zero * [0]
But for some reason which I cannot call why, it does not enter the first if statement where my input is:
[9,0.0,0,9,1,2,0,1,0,1,0.0,3,0,1,9,0,0,0,0,9]
The output is:
[9, 0.0, 9, 1, 2, 1, 1, 0.0, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0]
It outputs the wrong list on Python 3.6
While on python 3.8.2 it works fine.. (However I need to use 3.6 for this)
Where am I wrong? the if statement seems ok!
Thank you!
But for some reason which I cannot call why, it does not enter the first if statement where my input is:
You need to use ==
for comparing values. is
is used to compare identity in Python. See this for information on ==
vs is
in Python.
Try this:
def move_zeros(a):
r = [i for i in a if not isinstance(i, (float, int)) or str(i) not in ('0.0', '0')]
r += [0] * (len(a) - len(r))
return r
print(move_zeros([9,0.0,0,9,1,2,0,1,0,1,0.0,3,0,1,9,0,0,0,0,9]))
Outputs:
[9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]