Python Operators Equal To, Greater Than, Less Than, Not Equal To
Table of Contents
Python operators or Chain comparison:
Unlike the other programming languages, in Python you can compare various items using various python operators with chain comparison. For example
x > y > z
Is just a short form of:
x > y and y > z
This will evaluate to true only if both comparisons are true.
The general form is
a OP b OP c OP d …
Where OP is the python operator represents one of the various comparison operations you can use, and the letters represent arbitrarily
valid expressions.
“Note that 0 != 1 != 0 evaluates to True, even though 0 != 0 is False. Unlike the common mathematical
notation in which x != y != z means that x, y and z have contrasting values. Chaining == operations has
the natural meaning in most cases, since equality is generally transitive.”
Style
There is no abstract limit on how many items and python operators you use as long you have proper syntax:
1 > -1 < 2 > 0.5 < 100 != 24
The above returns true if each relation returns true. However, using convoluted chaining is not a good style. A good chaining will be “directional”, not more complicated than
1 > x > -4 > y != 8
Side effects
As soon as one comparison returns False, the expression evaluates immediately to False, skipping all remaining comparisons.
Note that the expression exp in a > exp > b will be calculated only once, whereas in the case of
a > exp and exp > b
exp will be computed over again if a > exp is true.
Amazon Purchase Links:
*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!
Python Operators difference between “is” and “==”:
A common pitfall is confusing the equality python operators is and ==.
a == b compares the value of a and b.
a is b will compare the identities of a and b.
To illustrate:
1 2 3 4 5 6 7 8 9 10 11 |
a = 'Python is fun!' b = 'Python is fun!' a == b # returns True a is b # returns False a = [1, 2, 3, 4, 5] b = a # b references a a == b # True a is b # True b = a[:] # b now references a copy of a a == b # True a is b # False [!!] |
Basically, is can be thought of as shorthand for id(a) == id(b).
before this, there are quirks of the run-time environment that further complicate things. Short strings and small integers will return True when related with is, due to the Python machine attempting to use less memory for identical objects.
1 2 3 4 5 6 |
a = 'short' b = 'short' c = 5 d = 5 a is b # True c is d # True |
But longer strings and larger integers will be stored separately.
1 2 3 4 5 6 7 8 9 10 11 |
a = 'not so short' b = 'not so short' c = 1000 d = 1000 a is b # False c is d # False |
You should use is to test for None:
if myvar is not None:
not None
pass
if myvar is None:
None
pass
The use of is is to test for a “sentinel” (i.e. a unique object).
sentinel = object()
def myfunc(var=sentinel):
if var is sentinel:
value wasn’t provided
pass
else:
value was provided
Pass
Python Operators Greater than or less than:
x > y
x < y
These python operators correlated two types of values, they’re the less than and greater than operators. For numbers this simply compares the numerical values to see which is larger:
1 2 3 4 5 6 7 8 9 10 11 |
12 > 4 # True 12 < 4 # False 1 < 4 # True |
For strings, they will compare lexicographically, which is similar to alphabetical order but not truly the same.
1 2 3 4 5 6 7 8 9 10 11 |
"alpha" < "beta" # True "gamma" > "beta" # True "gamma" < "OMEGA" # False |
In these connections, lowercase letters are considered ‘greater than’ uppercase, which is why “gamma” < “OMEGA” is false. If they were all uppercase it would return the normal alphabetical ordering result:
“GAMMA” < “OMEGA”
True
Each type defines it’s calculation with the < and > operators differently, so you should investigate what the operators means with a given type before using it.
Python Operators Not equal to != :
x != y
This python operator returns True if x and y are not equal and if equals its returns False.
1 2 3 4 5 6 7 8 9 10 11 |
12 != 1 # True 12 != '12' # True '12' != '12' # False |
Python Operators Equal Equal to:
x == y
This python operators evaluates if x and y are the same value and returns the result as a boolean value. Generally both
the value and type must be matched, so the int 12 is not the same as the string ’12’.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
12 == 12 # True 12 == 1 # False '12' == '12' # True 'spam' == 'spam' # True 'spam' == 'spam ' # False '12' == 12 # False |
Note that each type has to define a function that will be used to calculate if two values are the same. For builtin types these functions behave as you’d hope, and just calculate things based on being the same value. However procedure types could define equality testing as whatever they’d like, including always returning True or always returning False.
python Comparing object operators:
In order to compare the equality of procedure classes, you can override == and != by defining eq and ne
methods. You can also override lt (<), le (<=), gt (>), and ge (>). Note that you only need to
override two comparison approach, and Python can handle the rest (== is the same as not < and not >, etc.)
class Foo(object):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
def __init__(self, item): self.my_item = item def __eq__(self, other): return self.my_item == other.my_item a = Foo(5) b = Foo(5) a == b # True a != b # False a is b # False |
Note that this simple comparison consider that other (the object being compared to) is the same object type.
Comparing to another type will throw an error:
class Bar(object):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
def __init__(self, item): self.other_item = item def __eq__(self, other): return self.other_item == other.other_item def __ne__(self, other): return self.other_item != other.other_item c = Bar(5) a == c # throws AttributeError: 'Foo' object has no attribute 'other_item' |
Checking isinstance() or similar will help prevent this (if desired).