Python Not Equal

Python not equal comparison is done with !=, the not equal operator. The result of the operation is a Boolean.

>>> 3 != 8
True
>>> 3 != 3
False
>>> 'test' != 'test'
False

The most common use of the not equal operator is to decide the flow of the application:

a, b = 3, 5
if a != b:
   print('a and b are not equal')
else:
   print('a and b are equal')

Comparing Objects with !=

Python not equal operator compares the value of objects, that’s in contrast to the Python is not operator that compares if they are actually different objects. For example:

>>> a = [2, 3]
>>> b = [2, 3]
>>> a != b
False
>>> a is not b
True

Comparing Lists in Python

You can use the not equal operator to compare lists:

>>> [2, 3] != [2, 3]
False
>>> [3, 2] != [2, 3]
True

Comparing Tuples in Python

You can use the not equal operator to compare tuples:

>>> (2, 3) != (2, 3)
False
>>> (3, 2) != (2, 3)
True

Comparing Sets in Python

You can use the not equal operator to compare sets:

>>> set([2, 3]) != set([2, 3])
False
>>> set([3, 2]) != set([2, 3])
False
>>> set([8, 2]) != set([2, 3])
True

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'}
False
>>> {5: 'b', 2: 3} != {2: 3, 5: 'b'}
False
>>> {3: 3, 5: 'b'} != {2: 3, 5: 'b'}
True

As you can see the order doesn’t make a difference in the comparison, because the Dictionary’s order doesn’t matter.