Python Less Than

Python less than comparison is done with <, the less than operator. The result of the operation is a Boolean.

>>> 3 < 8
True
>>> 8 < 3
False

The most common use of the less than operator is to decide the flow of the application:

a, b = 3, 5
if a < b:
   print('a is less than b')
else:
   print('a is not less than b')

Comparing Strings in Python

You can use the less than operator to compare strings. It will use lexicographical order to do the comparison, meaning that it compares each item in order. It first compares the first two chars in each string, if they are equal it goes to the next char, and so on.

>>> 'aa' < 'bb' 
True
>>> 'aa' < 'ab'
True
>>> 'ac' < 'ab'
False
>>> 'a' < 'B'
False
>>> 'B' < 'a'
True

Comparing Lists in Python

It’s the same lexicographical comparison as with Strings, each item is compared in the order that it is in the list.

>>> [1, 2] < [2, 3]
True
>>> [2, 1] < [2, 3]
True
>>> [2, 4] < [2, 3]
False

Comparing Tuples in Python

It’s the same lexicographical comparison as with Strings, each item is compared in the order that it is in the tuple.

>>> (1, 2) < (2, 3)
True
>>> (2, 1) < (2, 3)
True
>>> (2, 4) < (2, 3)
False

Comparing Set and Dictionaries in Python

You can not use the less than operator to compare sets and dictionaries in Python.

>>> set([3]) < set([4])
False # Doesn't work correctly
>>> {5: 'b', 2: 3} < {2: 3, 5: 'b'}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'dict' and 'dict'