Python Less Than (<) Operator

Python Less Than Operator

Python Less Than operator is used to compare if an operand is less than other operand.

Syntax

The syntax of less than comparison operator is

operand_1 < operand_2

Less than operator returns a boolean value. True if operand_1 is less than operand_2 in value. Otherwise, it returns False. If the operands are sequences like strings, lists, tuple, etc., corresponding elements are compared to compute the result.

Example 1

In this example, we will compare two integers, x and y, and check if x is less than y.

Python Program

x = 5
y = 12
result = x < y
print(result) #True

x = 8
y = 7
result = x < y
print(result) #False
Run Code Copy

Output

True
False

For x = 5, and y = 12, x < y returns True.

For x = 8, and y = 7, x < y returns False.

Example 2: Less Than Operator with String Operands

You can compare if a Python String is less than other string. Python considers lexicographic order of alphabets, or you could say the ASCII value. In that case, the alphabet ‘a’ is less than alphabet ‘b’, and ‘b’ is less than ‘c’, and so on. The same explanation holds for other possible characters in a string.

While comparing, the first character of each string is compared. If they are equal, next characters are compared, else the result is returned.

In this example, we will compare two strings, x and y, and check if one string is less than other.

Python Program

x = 'apple'
y = 'banana'
z = 'cherry'
k = 'Apple'
print(x < y) #True
print(y < z) #True
print(x < z) #True
print(x < k) #False
Run Code Copy

Output

True
True
True
False

'a' is less than 'b' and therefore 'apple' is less than 'banana'. So, x<y returned True. Similary for y<z ad x<z.

'a' is greater than 'A'. Therefore 'apple' < 'Apple' returned False.

Example 3: Less Than Operator with Lists

Just like strings, Python Lists can be compared too. And the comparison happens in the same way.

In this example, we will compare some lists.

Python Program

x = [41, 54, 21]
y = [98, 8]
z = [41, 54, 4, 6]
print(x < y) #True
print(y < z) #False
print(x < z) #False
Run Code Copy

Output

True
False
False

[41, 54, 21] less than [98, 8] first compares the elements 41 and 98. The result is straight away True and the operator returns True.

[98, 8] less than [41, 54, 4, 6] first compares the elements 98 and 41. The result is straight away False and the operator returns False.

[41, 54, 21] less than [41, 54, 4, 6] first compares the elements 41 and 41. No result. Then 54 and 54 are compared. Still no result. Then 21 and 4 are compared. This returns False for 21 < 4 .

Summary

In this tutorial of Python Examples, we learned how to compare two values or sequences like strings, lists, etc., using less than comparison operator.

Related Tutorials

Code copied to clipboard successfully 👍