float identity comparison in Python lambda function

╄→尐↘猪︶ㄣ 提交于 2021-01-28 12:14:15

问题


Why does the following happen with Python's lambdas (in both Python 2 and 3)?

>>> zero = lambda n: n is 0
>>> zero(0)
True
>>> zero = lambda n: n is 0.0
>>> zero(0.0)
False

回答1:


The most common Python implementation store a number of small integers as "constant" or "permanent" objects in a pre-allocated array: see the documentation. So, these numbers can be recongized as identical objects using the is operator. This is not done for floats.

If you were to compare the numbers using the equality operator ==, you'd get identical behaviour for ints as well as floats.

Note that 0 is an integer, and 0.0 is a float.

If you were to use a larger integer instead of 0 (for example, changing the lambda to test for n is 5000, and also plugging 5000 into the function), it would return False again, because the two 5000 numbers would be different objects internally.


Some examples for clarity:

>>> zero = lambda n: n is 0
>>> zero(0)
True

is returns True here because both instances of 0 are literally the same object internally (which is what is checks for).

>>> zero = lambda n: n == 0
>>> zero(0)
True

== returns True this time because the two numbers are equal, not necessarily because they are identical objects internally.

>>> zero = lambda n: n is 5000
>>> zero(5000)
False

This returns False because 5000 is too big a number, it no longer fits in the range of numbers that get pre-allocated internally.

>>> zero = lambda n: n is 0.0
>>> zero(0.0)
False

This returns False again because 0.0 is a float, and for floats there isn't any pre-allocating internally like there is for a limited range of integers, so this is actually exactly the same case as above.

>>> zero = lambda n: n == 0.0
>>> zero(0.0)
True

Using == instead of is results in comparing the numbers again instead of internal objects, so now we get True.



来源:https://stackoverflow.com/questions/49447925/float-identity-comparison-in-python-lambda-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!