Test 0 and false since false is 0

Rick Johnson rantingrickjohnson at gmail.com
Thu Jul 6 22:46:26 EDT 2017


On Thursday, July 6, 2017 at 9:29:29 PM UTC-5, Sayth Renshaw wrote:
> I was trying to solve a problem and cannot determine how to filter 0's but not false.
> 
> Given a list like this
> ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9]
> 
> I want to be able to return this list
> ["a","b",None,"c","d",1,False,1,3,[],1,9,{},9,0,0,0,0,0,0,0,0,0,0]
> 
> However if I filter like this 
> 
> def move_zeros(array):
>     l1 = [v for v in array if v != 0]
>     l2 = [v for v in array if v == 0]
>     return l1 + l2
> 
> I get this 
> ['a', 'b', None, 'c', 'd', 1, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, False, 0, 0, 0, 0, 0, 0, 0] 
> 
> I have tried or conditions of v == False etc but then the 0's being false also aren't moved. How can you check this at once?

Yep. This is a common pitfall for noobs, as no logic can
explain to them why integer 0 should bool False, and integer
1 should bool True. But what's really going to cook your
noodle is when you find out that any integer greater than 1
bools True. Go figure! They'll say it's for consistency
sake. But i say it's just a foolish consistency.

You need to learn the subtle difference between `==` and
`is`.

    ## PYTHON 2.x
    >>> 1 == True
    True
    >>> 1 is True
    False
    >>> 0 == False
    True
    >>> 0 is False
    False



More information about the Python-list mailing list