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.
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
>>> 20 == 20.0
Do the objects have different values?
>>> 12 != 20
>>> 20 != 20.0
Is the first object bigger than the second?
>>> 12 > 20
>>> 20 > 20.0
Is the first object smaller than the second?
>>> 12 < 20
>>> 20 < 20.0
Is the first object bigger than or equal to the second?
>>> 12 >= 20.0
>>> 20 >= 20.0
Is the first object smaller than or equal to the second?
>>> 12 <= 20
>>> 20 <= 20.0
It is possible to check if a number sits in range of values by grouping two comparison expressions:
>>> n = 22 >>> 10 < n < 100
>>> n = 1 >>> 10 < n < 100
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
>>> 10 is 10.0
In this example, the two objects have the same value but different identities – the first one is an
int, and the second is a
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
Let’s have a look at examples with different data types:
>>> bool('hello') # string
>>> bool('') # empty string
>>> bool(['a', 'b', 'c']) # list
>>> bool() # empty list
>>> bool(1.1) # float
>>> bool(0.0) # float zero