Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Less Than Operator: Syntax and Comparison Behavior

Understand how Python's less than operator works for numbers, strings, and custom objects, including chaining, overloading, and common pitfalls.

~4 min readPython
#comparison operators#Python syntax#operator overloading#conditional logic
Diagram showing Python less than operator comparing two values with a left-to-right arrow.

The Python less than operator (<) returns True when the left operand is smaller than the right operand. It is a binary comparison operator that works with built-in types and can be customized for user-defined classes. This article explains its syntax, runtime behavior, and practical usage for working developers.

How the Less Than Operator Works in Python

The less than operator is defined by the language grammar as a comparison operator. When you write a < b, Python first tries type(a).__lt__(a, b). If that method is missing or returns NotImplemented, Python may try the reflected comparison b > a on the right operand. If neither side supports the comparison, Python raises a TypeError.

python
result = 3 < 5 print(result) # True

For built-in numeric types, the comparison is straightforward and performs a direct value comparison. For strings, Python compares lexicographically using Unicode code points. This means that string ordering follows the character encoding order, not necessarily alphabetical order in a human sense.

python
print("apple" < "banana") # True print("Apple" < "apple") # True, because 'A' (65) < 'a' (97)

Comparing Numbers and Strings

Numeric comparison is the most common use of the less than operator. Integers and floats support < with the usual mathematical ordering. Complex numbers do not support <; they have no natural total order, so comparing them with < raises a TypeError.

python
print(1.5 < 2) # True print(10 < 10) # False # print(1+2j < 2+1j) # TypeError: '<' not supported between instances of 'complex' and 'complex'

String comparison is based on the Unicode code point of each character, from left to right. The comparison stops at the first differing character. If one string is a prefix of the other, the shorter string is considered smaller.

python
print("cat" < "catalog") # True print("cat" < "car") # False, because 't' (116) > 'r' (114)

When comparing mixed types, Python generally raises a TypeError unless the types explicitly support cross-type comparison. For example, comparing an integer to a string is not allowed.

python
# print(1 < "2") # TypeError: '<' not supported between instances of 'int' and 'str'

Chained Comparisons and Short-Circuit Behavior

Python supports chained comparisons, allowing multiple comparison operators to be combined in a single expression. The expression a < b < c is equivalent to a < b and b < c, but b is evaluated only once. This is a key difference from many other languages where such chaining is not syntactically valid.

python
x = 5 print(1 < x < 10) # True print(1 < x < 4) # False

The chained comparison short-circuits: if the first comparison is False, the second is not evaluated. This can be useful when the second comparison has side effects or is computationally expensive.

python
def get_value(): print("called") return 7 print(1 < 0 < get_value()) # False, get_value() is never called

Chaining is not limited to <; you can mix operators such as <=, >, >=, ==, and != in the same chain. For example, a < b == c is valid and evaluates as a < b and b == c.

Overloading Less Than for Custom Classes

To make instances of your own classes support the < operator, define the __lt__ method. This method should return a boolean or a value that can be truth-tested. It is common to implement __lt__ for sorting and ordering.

python
class Product: def __init__(self, name, price): self.name = name self.price = price def __lt__(self, other): if not isinstance(other, Product): return NotImplemented return self.price < other.price p1 = Product("A", 10) p2 = Product("B", 20) print(p1 < p2) # True

Returning NotImplemented for unsupported types allows Python to try the reflected operation on the other operand, which is the correct pattern for binary operators. If neither side supports the operation, Python raises TypeError.

When you define __lt__, consider also defining __eq__ to maintain consistency. The default __eq__ compares object identity, which may not align with your ordering logic. For a total ordering, you might also implement __le__, __gt__, and __ge__, or use the functools.total_ordering decorator to fill in the missing methods from just __lt__ and __eq__.

python
from functools import total_ordering @total_ordering class Product: def __init__(self, name, price): self.name = name self.price = price def __lt__(self, other): if not isinstance(other, Product): return NotImplemented return self.price < other.price def __eq__(self, other): if not isinstance(other, Product): return NotImplemented return self.price == other.price print(Product("A", 10) <= Product("B", 20)) # True

Common Mistakes and Edge Cases

The less than operator is often misused when comparing None or other sentinel values. In Python, None is not comparable to numbers in a meaningful way; None < 1 raises a TypeError. If you need to handle missing values, check for None explicitly before comparison.

python
value = None # if value < 10: # TypeError if value is not None and value < 10: pass

Another edge case is comparing floating-point numbers. Due to binary representation, direct comparisons can produce unexpected results. For example, 0.1 + 0.2 < 0.3 evaluates to False because the sum is slightly larger than 0.3. Use a tolerance or the math.isclose function when exact equality is not reliable.

python
import math print(0.1 + 0.2 < 0.3) # False print(math.isclose(0.1 + 0.2, 0.3)) # True

When overloading __lt__, a common mistake is to forget to handle the case where other is of an incompatible type. Returning NotImplemented is the correct approach, as it allows Python to attempt a reverse operation or raise a clear error.

Keep equality consistent with ordering in custom classes. If __lt__ treats two objects as equivalent (neither is less than the other) while __eq__ says they are different, code that mixes ordering and equality comparisons may behave unexpectedly.

Performance and Maintainability Considerations

Built-in numeric comparisons are implemented in C and are efficient; leave them alone unless profiling shows they are a bottleneck. String comparison compares code points from left to right, so it stops at the first difference; strings know their length, so a length mismatch can be detected quickly. Custom __lt__ methods can introduce significant overhead if they perform complex computations or I/O. When sorting large collections, the comparison method is called many times, so keep it lightweight. Avoid recomputing expensive attributes inside __lt__; precompute and cache them if necessary.

From a maintainability perspective, overloading < should follow the principle of least surprise. If your class has a natural ordering, implement it consistently and document the ordering criteria. If the ordering is not obvious, consider providing a separate key function for sorting instead of overloading the operator.

python
# Instead of overloading __lt__, use a key function for sorting products.sort(key=lambda p: p.price)

This approach keeps the operator semantics clear and avoids hidden side effects. It also makes the sorting logic explicit at the call site, which is often easier to maintain than relying on a custom comparison method.

Finally, be aware that set objects use < to mean proper subset, not ordering by size or element order. For example, {1} < {1, 2} is True, but {1, 2} < {1, 3} is False. Dictionaries do not support <; comparing them with < raises a TypeError. If you need a custom ordered comparison for either type, define your own helper or key function.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.