When comparing two objects it is important to make a distinction between value and identity.

Python has comparison and identity operators to compare two objects and decide the relation between them.

Comparing values

Comparison operators allow us to compare two objects numerically. The result of a comparison expression is always a boolean value.

Here is an overview of all the comparisons we can make between two values:

Do the objects have the same value?

>>> 12 == 20
False
>>> 20 == 20.0
True

Do the objects have different values?

>>> 12 != 20
True
>>> 20 != 20.0
False

Is the first object bigger than the second?

>>> 12 > 20
False
>>> 20 > 20.0
False

Is the first object smaller than the second?

>>> 12 < 20
True
>>> 20 < 20.0
False

Is the first object bigger than or equal to the second?

>>> 12 >= 20.0
False
>>> 20 >= 20.0
True

Is the first object smaller than or equal to the second?

>>> 12 <= 20
True
>>> 20 <= 20.0
True

It is possible to check if a number sits in range of values by grouping two comparison expressions:

>>> n = 22
>>> 10 < n < 100
True
>>> n = 1
>>> 10 < n < 100
False

Comparing identity

Two objects can have the same value and still have different identities – they are not the same ‘thing’.

To compare identities we use the identity operator is:

>>> 10 is 10.0
False

In this example, the two objects have the same value but different identities – the first one is an int, and the second is a float.

Testing ‘truthiness’

Every object in Python can be converted into a boolean. The general rule is that 0 and any empty collections are converted to False, and anything else is converted to True.

Let’s have a look at examples with different data types:

>>> bool('hello') # string
True
>>> bool('') # empty string
False
>>> bool(['a', 'b', 'c']) # list
>>> True
>>> bool([]) # empty list
False
>>> bool(1.1) # float
True
>>> bool(0.0) # float zero
False
>>> bool(None)
False
Last edited on 01/09/2021