Value Comparison Operators
Comparison operators are used to determine equality of two data values between members of the same type. These comparison operators are supported for all built-in types. Comparisons yield true or false values, based on the validity of the comparison expression. Python chooses to interpret these values as the plain integers 0 and 1 for false and true, respectively, meaning that each comparison will result in one of those two
possible values. A list of Python’s value comparison operators is given in following Table.
Operator | function |
---|---|
expr1 < expr2 | expr1 is less than expr2 |
expr1 > expr2 | expr1 is greater than expr2 |
expr1 <= expr2 | expr1 is less than or equal to expr2 |
expr1 >= expr2 | expr1 is greater than or equal to expr2 |
expr1 == expr2 | expr1 is equal to expr2 |
>expr1 != expr2 | expr1 is not equal to expr2 (C-style) |
expr1 <> expr2 | expr1 is not equal to expr2 (ABC/Pascal-style) |
Note that comparisons performed are those that are appropriate for each data type. In other words, numeric types will be compared according to numeric value in sign and magnitude, strings will compare lexicographically, etc.
Example
>>> 2==2 True >>> 2.46<=8.33 True >>> 'abc'=='xyz' False >>> 'abc' > 'xyz' False >>> 'abc' < 'xyz' True >>> [3,'abc'] == ['abc',3] False >>> [3,'abc'] == [3,'abc'] True >>> 3 < 4 < 7 True >>> 4 > 3 == 3 True >>> 4 < 3 < 5 != 2 < 7 False
We would like to note here that comparisons are strictly between object values, meaning that the comparisons are between the data values and not the actual data objects
themselves.