Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

0 is 0 == 0 (#evaluates to True?) [duplicate]

Tags:

This baffles me. Even without knowing the precedence order, one can check that the two possible ways to gather the expression would give False :

>>> (0 is 0) == 0 False >>> 0 is (0 == 0) False 

But

>>> 0 is 0 == 0 True 

How come?

like image 569
Aguy Avatar asked Jul 29 '16 07:07

Aguy


People also ask

Is 0 == 0 in JS?

In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.

Does the integer 0 == false?

Treating integers as boolean values C++ does not really have a boolean type; bool is the same as int. Whenever an integer value is tested to see whether it is true of false, 0 is considered to be false and all other integers are considered be true.

Is 0 truthy or Falsy?

In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy. That is, all values are truthy except false , 0 , -0 , 0n , "" , null , undefined , and NaN .

Why does 0 0 have no answer?

One can argue that 0/0 is ​0, because 0 divided by anything is 0. Another one can argue that 0/0 is ​1, because anything divided by itself is 1. And that's exactly the problem! Whatever we say 0/0 equals to, we contradict one crucial property of numbers or another.


2 Answers

You are using comparison operator chaining. The expression is interpreted as:

(0 is 0) and (0 == 0) 

From the Comparisons documentation:

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

0 is 0 is true because Python interns small integers, an implementation detail, so you get (True) and (True) producing True.

like image 143
Martijn Pieters Avatar answered Oct 29 '22 14:10

Martijn Pieters


When chaining comparison operators in Python, the operators aren't actually applied to the result of the other operators, but are applied to the operands individually. That is x ? y ?? z (where ? and ?? are supposed to stand in for some comparison operators) is neither equivalent to (x ? y) ?? z nor x ? (y ?? z), but rather x ? y and y ?? z.

This is particularly useful for > and co., allowing you to write things like min < x < max and have it do what you want rather than comparing a boolean to a number (which would happen in most other languages).

like image 29
sepp2k Avatar answered Oct 29 '22 15:10

sepp2k