Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i move just Zero to the end of my list and not False in python

Tags:

python

def move_zeros(array):
    for element in array:
        if element == 0 and type(element) is not bool:
            array.append(array.pop(array.index(element)))
    return array

print(move_zeros([False,1,0,1,2,0,1,3,"a"]))

My result is [1, 1, 2, 1, 3, 'a', False, 0, 0] I don't want False to move, my program sees False as 0.


2 Answers

This is coming about because you're operating on the list while looping over it, as well as the issue that you've correctly identified, that False == 0 and 0 == 0 both are True in Python. One way to deal with this is the following, using is instead of == to check equality to 0:

def move_zeros(a):
    return [x for x in a if x is not 0] + [x for x in a if x is 0]

print(move_zeros([False,1,0,1,2,0,1,3,"a"]))

Output:

[False, 1, 1, 2, 1, 3, 'a', 0, 0]

Note that the use of is to compare integers is not safe in general because integers outside of the range (-5, 256) have different ids from each other (see this question). In our case however, we are just using 0, so the solution above is safe.

like image 159
CDJB Avatar answered Dec 01 '25 10:12

CDJB


Simple solution and showing that your check is actually ok:

>>> sorted(array, key=lambda x: x == 0 and type(x) is not bool)
[False, 1, 1, 2, 1, 3, 'a', 0, 0]

Or compare with the False singleton:

>>> sorted(array, key=lambda x: x == 0 and x is not False)
[False, 1, 1, 2, 1, 3, 'a', 0, 0]

Or if you're feeling playful, chained comparisons:

>>> sorted(array, key=lambda x: 0 == x is not False)
[False, 1, 1, 2, 1, 3, 'a', 0, 0]
like image 24
Stefan Pochmann Avatar answered Dec 01 '25 11:12

Stefan Pochmann