15. Comparisons

Parameter Details

xFirst item to be compared

ySecond item to be compared

Section 15.1: Chain Comparisons

You can compare multiple items with multiple comparison operators with chain comparison. For example

z

is just a short form of:

and 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 represents one of the multiple comparison operations you can use, and the letters represent arbitrary valid expressions.

Note that 0 != != 0 evaluates to True, even though 0 != 0 is False. Unlike the common mathematical notation in which != != z means that xy and z have dierent values. Chaining == operations has the natural meaning in most cases, since equality is generally transitive.

Style

There is no theoretical limit on how many items and comparison operations you use as long you have proper syntax:

0.5 100 != 24

The above returns True if each comparison returns True. However, using convoluted chaining is not a good style. A good chaining will be “directional”, not more complicated than

4 != 8

Side eects

As soon as one comparison returns False, the expression evaluates immediately to False, skipping all remaining comparisons.

Note that the expression exp in exp b will be evaluated only once, whereas in the case of

exp and exp b

exp will be computed twice if exp is true.

Section 15.2: Comparison by `is` vs `==`

A common pitfall is confusing the equality comparison operators is and ==.

a== b compares the value of a and b.

ais b will compare the identities of a and b. To illustrate:

‘Python is fun!’ ‘Python is fun!’ == # returns True is # returns False

[12345]

a

# b references a

== b

# True

is b

# True

a[:]

# b now references a copy of a

== b

# True

is b

# False [!!]

Basically, is can be thought of as shorthand for id(a) == id(b).

Beyond this, there are quirks of the run-time environment that further complicate things. Short strings and small integers will return True when compared with is, due to the Python machine attempting to use less memory for identical objects.

‘short’ ‘short’ 5

5

is # True is # True

But longer strings and larger integers will be stored separately.

‘not so short’ ‘not so short’ 1000

1000

is # False is # False

You should use is to test for None:

if myvar is not None:

#not Nonepass

if myvar is None:

#None

pass

A 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 wasnt provided pass

else:

#value was providedpass

Section 15.3: Greater than or less than

y x y

These operators compare 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:

12 4

#True12 4

#False

4

#True

For strings they will compare lexicographically, which is similar to alphabetical order but not quite the same.

“alpha” “beta”

# True

“gamma” “beta”

# True

“gamma” “OMEGA”

# False

In these comparisons, lowercase letters are considered ‘greater than’ uppercase, which is why “gamma” “OMEGA” is false. If they were all uppercase it would return the expected alphabetical ordering result:

“GAMMA” “OMEGA”

# True

Each type defines it’s calculation with the < and > operators dierently, so you should investigate what the operators mean with a given type before using it.

Section 15.4: Not equal to

!= y

This returns True if x and y are not equal and otherwise returns False.

12 != 1

# True

12 != ’12’

# True

’12’ != ’12’

# False

Section 15.5: Equal To

== y

This expression evaluates if x and y are the same value and returns the result as a boolean value. Generally both type and value need to match, so the int 12 is not the same as the string ’12’.

12 == 12

#True12 == 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 evaluate if two values are the same. For builtin types these functions behave as you’d expect, and just evaluate things based on being the same value. However custom types could define equality testing as whatever they’d like, including always returning True or always returning False.

Section 15.6: Comparing Objects

In order to compare the equality of custom 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 methods, and Python can handle the rest (== is the same as not < and not >, etc.)

class Foo(object):

def __init__(selfitem): self.my_item item

def __eq__(selfother):

return self.my_item == other.my_item

    

=

Foo(5)

 

=

Foo(5)

 

== b

# True

a

!= b

# False

a

is b

# False

Note that this simple comparison assumes that other (the object being compared to) is the same object type. Comparing to another type will throw an error:

class Bar(object):

def __init__(selfitem): self.other_item item

def __eq__(selfother):

return self.other_item == other.other_item def __ne__(selfother):

return self.other_item != other.other_item

Bar(5)

== # throws AttributeError: ‘Foo’ object has no attribute ‘other_item’

 

 

 

 

 

*This content is compiled from Stack Overflow Documentation, and the content is written by the beautiful people at Stack Overflow. 

  *This content is compiled from Stack Overflow Documentation, and the content is written by the beautiful people at Stack Overflow.  This work is licensed under cc by-sa.