Python Comparisons

Python Comparisons let you perform the comparison of multiple items by using Python programming language. Learn more.

Parameter Details

First item to be compared

Second item to be compared

Python Comparisons: Chain Comparisons

You can compare multiple items with multiple comparison 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 represents one of the multiple comparison operations you can use, and the letters represent arbitrary 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 different 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:

1>-1<2>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

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 evaluated only once, whereas in the case of

a > exp and exp > b

exp will be computed twice if a > exp is true.

Python Comparisons: Comparison by is vs ==

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

== b compares the value of a and b.

is b will compare the identities of a and b. To illustrate:
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).

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.

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.

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

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 wasn’t provided pass
else:
value was provided pass

Python Comparisons: Greater than or less than

x > 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
True 12<4
False
1 < 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 differently, so you should investigate what the operators mean with a given type before using it.

Python Comparisons: Not equal to

x != y

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

12!=1

True

12 != '12'

True

'12' != '12'

False

Python Comparisons: Equal To

x == 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
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 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.

Python Comparisons: 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(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 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(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).

Learn More:

Must Read Python Interview Questions

200+ Python Tutorials With Coding Examples

Python Language Basics TutorialPython String Representations of Class Instances
Python For Beginners TutorialPython Debugging Tutorial
Python Data Types TutorialReading and Writing CSV File Using Python
Python Indentation TutorialWriting to CSV in Python from String/List
Python Comments and Documentation TutorialPython Dynamic Code Execution Tutorial
Python Date And Time TutorialPython Code Distributing using Pyinstaller
Python Date Formatting TutorialPython Data Visualization Tutorial
Python Enum TutorialPython Interpreter Tutorial
Python Set TutorialPython Args and Kwargs
Python Mathematical Operators TutorialPython Garbage Collection Tutorial
Python Bitwise Operators TutorialPython Pickle Data Serialisation
Python Bolean Operators TutorialPython Binary Data Tutorial
Python Operator Precedance TutorialPython Idioms Tutorial
Python Variable Scope And Binding TutorialPython Data Serialization Tutorial
Python Conditionals TutorialPython Multiprocessing Tutorial
Python Comparisons TutorialPython Multithreading Tutorial
Python Loops TutorialPython Processes and Threads
Python Arrays TutorialPython Concurrency Tutorial
Python Multidimensional Arrays TutorialPython Parallel Computation Tutorial
Python List TutorialPython Sockets Module Tutorial
Python List Comprehensions TutorialPython Websockets Tutorial
Python List Slicing TutorialSockets Encryption Decryption in Python
Python Grouby() TutorialPython Networking Tutorial
Python Linked Lists TutorialPython http Server Tutorial
Linked List Node TutorialPython Flask Tutorial
Python Filter TutorialIntroduction to Rabbitmq using Amqpstorm Python
Python Heapq TutorialPython Descriptor Tutorial
Python Tuple TutorialPython Tempflile Tutorial
Python Basic Input And Output TutorialInput Subset and Output External Data Files using Pandas in Python
Python Files And Folders I/O TutorialUnzipping Files in Python Tutorial
Python os.path TutorialWorking with Zip Archives in Python
Python Iterables And Iterators Tutorialgzip in Python Tutorial
Python Functions TutorialStack in Python Tutorial
Defining Functions With List Arguments In PythonWorking with Global Interpreter Lock (GIL)
Functional Programming In PythonPython Deployment Tutorial
Partial Functions In PythonPython Logging Tutorial
Decorators Function In PythonPython Server Sent Events Tutorial
Python Classes TutorialPython Web Server Gateway Interface (WSGI)
Python Metaclasses TutorialPython Alternatives to Switch Statement
Python String Formatting TutorialPython Packing and Unpacking Tutorial
Python String Methods TutorialAccessing Python Sourcecode and Bytecode
Using Loops Within Functions In PythonPython Mixins Tutorial
Python Importing Modules TutorialPython Attribute Access Tutorial
Difference Betweeb Module And Package In PythonPython Arcpy Tutorial
Python Math Module TutorialPython Abstract Base Class Tutorial
Python Complex Math TutorialPython Plugin and Extension Classes
Python Collections Module TutorialPython Immutable Datatypes Tutorial
Python Operator Module TutorialPython Incompatibilities Moving from Python 2 to Python 3
Python JSON Module TutorialPython 2to3 Tool Tutorial
Python Sqlite3 Module TutorialNon-Official Python implementations
Python os Module TutorialPython Abstract Syntax Tree
Python Locale Module TutorialPython Unicode and Bytes
Python Itertools Module TutorialPython Serial Communication (pyserial)
Python Asyncio Module TutorialNeo4j and Cypher using Py2Neo
Python Random Module TutorialBasic Curses with Python
Python Functools Module TutorialTemplates in Python
Python dis Module TutorialPython Pillow
Python Base64 Module TutorialPython CLI subcommands with precise help output
Python Queue Module TutorialPython Database Access
Python Deque Module TutorialConnecting Python to SQL Server
Python Webbrowser Module TutorialPython and Excel
Python tkinter TutorialPython Turtle Graphics
Python pyautogui Module TutorialPython Persistence
Python Indexing And Slicing TutorialPython Design Patterns
Python Plotting With Matplotlib TutorialPython hashlib
Python Graph Tool TutorialCreating a Windows Service Using Python
Python Generators TutorialMutable vs Immutable (and Hashable) in Python
Python Reduce TutorialPython configparser
Python Map Function TutorialPython Optical Character Recognition
Python Exponentiation TutorialPython Virtual Environments
Python Searching TutorialPython Virtual Environment – virtualenv
Sorting Minimum And Maximum In PythonPython Virtual environment with virtualenvwrapper
Python Print Function TutorialCreate virtual environment with virtualenvwrapper in windows
Python Regular Expressions Regex TutorialPython sys Tutorial
Copying Data In Python TutorialChemPy – Python package
Python Context Managers (“with” Statement) TutorialPython pygame
Python Name Special Variable TutorialPython pyglet
Checking Path Existence And Permissions In PythonWorking with Audio in Python
Creating Python Packages TutorialPython pyaudio
Usage of pip Module In Python TutorialPython shelve
Python PyPi Package Manager TutorialIoT Programming with Python and Raspberry PI
Parsing Command Line Arguments In Pythonkivy – Cross-platform Python Framework for NUI Development
Python Subprocess Library TutorialPandas Transform
Python setup.py TutorialPython vs. JavaScript
Python Recursion TutorialCall Python from C#
Python Type Hints TutorialPython Writing Extensions
Python Exceptions TutorialPython Lex-Yacc
Raise Custom Exceptions In PythonPython Unit Testing
Python Commonwealth Exceptions TutorialPython py.test
Python urllib TutorialPython Profiling
Web Scraping With Python TutorialPython Speed of Program
Python HTML Parsing TutorialPython Performance Optimization
Manipulating XML In PythonPython Security and Cryptography
Python Requests Post TutorialSecure Shell Connection in Python
Python Distribution TutorialPython Anti Patterns
Python Property Objects TutorialPython Common Pitfalls
Python Overloading TutorialPython Hidden Features
Python Polymorphism TutorialPython For Machine Learning
Python Method Overriding TutorialPython Interview Questions And Answers For Experienced
Python User Defined Methods TutorialPython Coding Interview Questions And Answers
Python Programming Tutorials With Examples

Other Python Tutorials

Leave a Comment