Suppose we want some block of code to be executed when both 'a' and 'b' are equal to say 5. Then we can write like :
if a == 5 and b == 5:     # do something   But a few days ago, I just involuntarily wrote a similar condition check as :
if a == b and b == 5:     # do something    which made me think, is there any difference between the two ? Also, there is one other way,
if a == b == 5:     # do something   Is there any difference, any difference in terms of process of evaluation or execution or time taken ? and also which one is the better or which is better to use?
Is it related to the concept of transitivity ?
Answer 55bd536a9113cbf7cb00051bThe == operator checks to see if two operands are equal by value. The === operator checks to see if two operands are equal by datatype and value.
“=” assigns a value to a variable, while “==” verifies the Python equality of two different variables.
The main difference between the == and === operator in javascript is that the == operator does the type conversion of the operands before comparison, whereas the === operator compares the values as well as the data types of the operands.
== and is are two ways to compare objects in Python. == compares 2 objects for equality, and is compares 2 objects for identity.
Since they are basically equivalent, you could also consider the way you read/think about the code:
if a == 5 and b == 5:   # do something   can be read as "if a equals 5 and b equals 5, then do ...". You have to think/conclude, that then also a will be equal to b.
This is opposite to the next example:
if a == b and b == 5:   # do something    This reads as "if a is equal to b and b equal to 5" and you have to conclude that then also a will be equal to 5
This is why I prefer the last example:
if a == b == 5:   # do something   If you are familiar with Python (thanks to Itzkata) it is immediately clear that all three things must be equal (to 5). If however people with less experience in Python (but programming skills in other languages) see this, they might evaluate this to
if (a == b) == 5:   which would compare the boolean result of the first comparison with the integer 5, which is not what Python does and might lead to different results (consider for example with a=0, b=0: a==b==0 is true while (a==b) == 0 is not!
The manual says:
There are eight comparison operations in Python. They all have the same priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example, 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).
There might even be a difference, for example if evaulating b in your example would have a side effect.
Regarding transitivity, you are right.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With