osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Test 0 and false since false is 0


On 2017-07-09, Paul D. DeRocco <pderocco at ix.netcom.com> wrote:
>> From: Sayth Renshaw
>> 
>> I have been reading this solution 
>> > >>> after = sorted(before, key=lambda x: x == 0 and type(x) == int)
>> 
>> it is really good, however I don't understand it enough to 
>> reimplement something like that myself yet.
>> 
>> Though I can that lambda tests for 0 that is equal to an int 
>> why does sorted put them to the end?
>
> Because the expression "x == 0 and type(x) == int" has a value of either
> False or True, and it sorts all the False values before the True values,
> leaving the order within those sets unchanged.
>
> That said, "x is 0" is even simpler.

And wrong.

Two equivalent integer objects _might_ be the same object, but that's
not guaranteed.  It's an _implementation_detail_ of CPython that small
integers are cached:

  >>> x =  0
  >>> x is 0
  True

But larger integers aren't:

  >>> a =  123412341234
  >>> a is 123412341234
  False

The first example could have returned False and been correct.

-- 
Grant Edwards               grant.b.edwards        Yow! TONY RANDALL!  Is YOUR
                                  at               life a PATIO of FUN??
                              gmail.com