Python equal comparison is done with ==
, the equal operator. The result of the operation is a Boolean.
>>> 3 == 3
True
>>> 3 == 8
False
>>> 'test' == 'test'
True
The most common use of the equal operator is to decide the flow of the application:
a, b = 3, 5
if a == b:
print('a and b are equal')
else:
print('a and b are not equal')
Comparing Objects with ==
Python equal operator compares the value of objects, that’s in contrast to the Python is
operator that compares if they are actually the same object. For example:
>>> a = [2, 3]
>>> b = [2, 3]
>>> a == b
True
>>> a is b
False
Comparing Lists in Python
You can use the equal operator to compare lists:
>>> [2, 3] == [2, 3]
True
>>> [3, 2] == [2, 3]
False
Comparing Tuples in Python
You can use the equal operator to compare tuples:
>>> (2, 3) == (2, 3)
True
>>> (3, 2) == (2, 3)
False
Comparing Sets in Python
You can use the equal operator to compare sets:
>>> set([2, 3]) == set([2, 3])
True
>>> set([3, 2]) == set([2, 3])
True
>>> set([8, 2]) == set([2, 3])
False
As you can see the order of the initial list doesn’t make a difference in the comparison, because the Set’s order doesn’t matter.
Comparing Dictionaries in Python
You can use the equal operator to compare dictionaries:
>>> {2: 3, 5: 'b'} == {2: 3, 5: 'b'}
True
>>> {5: 'b', 2: 3} == {2: 3, 5: 'b'}
True
>>> {3: 3, 5: 'b'} == {2: 3, 5: 'b'}
False
As you can see the order doesn’t make a difference in the comparison, because the Dictionary’s order doesn’t matter.