PythonPython Operators and ExpressionsPython comparison operators
What are comparison operators?
Question 43 of 88 · Updated
On this page
- 1. The six comparison operators
- 2. Comparing numeric values
- 3. Comparing strings, lists and tuples
- 4. Comparisons involving sets and dictionaries
- 5. Chained comparisons
- 6. Value equality versus object identity
- 7. Floating-point comparisons and NaN
- 8. Custom comparisons and dataclasses
- 9. NotImplemented is not False
- 10. Practical example: validate a score range
- 11. Practical example: sort using explicit comparison keys
- 12. Unsupported comparisons and common mistakes
- Frequently asked questions
- What are comparison operators used for?
- Does Python allow chained comparisons?
- Can different types compare equal?
- Does Python compare strings by length?
- Are equality and ordering always supported together?
- Interview-ready answer
- Official references
Comparison operators compare two values to determine whether they are equal, unequal or ordered relative to each other. Python provides six principal value comparison operators: ==, !=, <, <=, > and >=. For ordinary scalar values, these operations return True or False.
They are essential for conditions, validation, sorting, filtering and implementing business rules. Python also supports identity and membership comparisons, which answer different questions and are covered separately in the operator curriculum.
1. The six comparison operators#
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 3 == 3 | True |
!= | Not equal to | 3 != 4 | True |
< | Less than | 3 < 4 | True |
<= | Less than or equal to | 3 <= 3 | True |
> | Greater than | 4 > 3 | True |
>= | Greater than or equal to | 4 >= 4 | True |
PYTHONprint(3==3,3!=4,3<4,3<=3,4>3,4>=4)
Output:
True True True True True TrueEquality compares values according to their types' equality semantics. Ordering comparisons express a relationship such as less than or greater than. Not all Python objects define meaningful ordering, even when equality is supported.
The ordinary assignment symbol = is not an equality test. Use == to compare values and = to bind or update an assignment target.
2. Comparing numeric values#
Compatible built-in numeric types can compare equal even when their types differ.
PYTHONprint(1==1.0, True==1, 2**53+1==float(2**53+1))
Output on the tested binary64 platform:
True True FalseAn integer 1 and floating-point 1.0 represent equal numerical values. True is a bool, which is a subclass of int, and compares equal to 1.
The third comparison illustrates an important precision boundary. On a typical binary64 platform, converting 253 + 1 to float rounds the integer to 253. Python does not simply convert both operands to floats before comparing their values, so the equality test correctly returns False.
For built-in complex numbers, equality comparisons are supported, but ordinary ordering operators are not. A complex-number ordering requires an explicitly chosen criterion such as magnitude or phase, depending on the application.
3. Comparing strings, lists and tuples#
Strings are compared lexicographically using their Unicode code points. Lists and tuples compare lexicographically with sequences of the same respective type, provided the relevant element comparisons are supported.
PYTHONprint("Z"<"a", "cat"<"catalog", [1,9]<[2,0], (1,2)<(1,3))
Output:
True True True TrueLexicographic comparison examines corresponding elements until the first unequal pair determines the result. If all compared elements are equal and one sequence ends first, the shorter sequence precedes the longer one.
For example, [1, 9] is less than [2, 0] because 1 is less than 2. The later elements are not needed to decide this comparison.
String comparison is case-sensitive and is not automatically a language-specific dictionary order. If a product requires case-insensitive comparison, Unicode normalization or locale-aware sorting, select the appropriate explicit policy. Case folding alone is not a complete international collation solution.
For ordinary strings or sequences with a common prefix of length k, lexicographic comparison may examine O(k + 1) elements, bounded by the shorter length when both are finite. The actual cost includes the cost of comparing each element, which can itself involve complex objects or custom methods.
4. Comparisons involving sets and dictionaries#
Ordering does not always mean numerical or lexicographic order. Sets define comparison operators using subset and superset relationships.
PYTHONprint({1,2}<{1,2,3}, {1}<{2}, {"a":1}=={"a":1})
Output:
True False TrueFor sets, < means proper subset and <= means subset, while > and >= represent the corresponding superset relationships. Two sets can be incomparable: neither {1} nor {2} is a subset of the other. This is a partial ordering, not a total ordering suitable for ranking arbitrary sets.
Dictionary equality compares key-value associations. It does not require the same insertion order. Ordinary dictionaries do not implement less-than or greater-than ordering between dictionaries.
Always interpret a comparison according to the data type rather than assuming all comparison symbols have numerical semantics.
5. Chained comparisons#
Python allows multiple comparisons in one expression, such as 0 <= score <= 100. This expresses adjacent relationships and is especially useful for range checks.
PYTHONdef middle(): print("middle") return 5 print(0 < middle() < 10) print(10 < middle() < 20)
Output:
middle
True
middle
FalseIn the first comparison, the middle expression is evaluated once. Python tests 0 < 5 and then 5 < 10.
In the second comparison, the first relation, 10 < 5, is false, so the final comparison is skipped. The middle function is still called once for that expression.
The flowchart describes an expression of the form a < b < c. The middle operand is evaluated once if reached, and the right operand is evaluated only if the first comparison passes its truth test.
For ordinary scalar values, a < b < c is equivalent in truth value to a < b and b < c. However, the expanded expression can evaluate b twice, which matters when b is a function call or another expression with side effects.
Python does not evaluate the first comparison and then compare the resulting Boolean to the last operand. Parenthesizing a comparison can change its meaning: (a < b) < c is not a chained comparison.
For custom rich comparisons that return non-Boolean objects, intermediate results in a chain must support the necessary truth testing. The final result need not be a bool.
6. Value equality versus object identity#
PYTHONa=[1]; b=[1]; c=a print(a==b,a is b,a is c)
Output:
True False TrueThe first two lists contain equal elements, but they are different objects. The third name refers to the same object as a.
Use == for value comparison. Use is when object identity is the intended relationship, especially for singleton sentinels such as None. Do not rely on implementation-specific integer or string caching when comparing values.
Unlike value comparisons, identity testing cannot be customized through __eq__. A later dedicated identity lesson examines the distinction and its consequences in more depth.
7. Floating-point comparisons and NaN#
PYTHONimport math print(0.1+0.2==0.3, math.isclose(0.1+0.2,0.3)) n=float("nan") print(n==n,n!=n,n<0,n>=0)
Output on the tested platform:
False True
False True False FalseMany decimal fractions are not exactly representable as binary floating-point numbers. Consequently, an exact equality test may fail even when two computations are mathematically expected to be equal.
math.isclose uses relative and absolute tolerance criteria to compare approximate real numerical results. Choose tolerances appropriate to the units and error budget of the application. For values near zero, an explicit absolute tolerance can be necessary.
NaN is an unusual floating-point value: it does not compare equal to itself, and ordinary ordering comparisons involving NaN are false. Use math.isnan to detect a floating-point NaN rather than relying on a normal ordering comparison.
Do not replace all equality checks with approximate equality. Exact identifiers, discrete counts and equality requirements in data models may require exact comparisons. Approximate equality is also not generally transitive.
8. Custom comparisons and dataclasses#
Python's data model allows classes to define value comparison behavior through rich comparison methods.
| Operator | Corresponding special method |
|---|---|
== | __eq__ |
!= | __ne__ |
< | __lt__ |
<= | __le__ |
> | __gt__ |
>= | __ge__ |
Python applies these methods using its rich-comparison dispatch rules, including reflected comparisons and subclass considerations. An unsupported operand pairing can be indicated by returning NotImplemented.
The dataclasses module can generate comparison methods for simple structured values.
PYTHONfrom dataclasses import dataclass @dataclass(order=True) class Ticket: priority: int number: int print(Ticket(1,5)<Ticket(2,1),Ticket(1,5)==Ticket(1,5))
Output:
True TrueThe generated ordering compares the participating fields in declaration order, as though comparing tuples of their values. The generated comparison methods require both instances to have the identical type.
Here priority is compared first; number breaks ties in priority. This is appropriate only if that field order expresses the intended domain ordering. If the desired order differs, use an explicit key or define the class's comparison contract accordingly.
A class implementing equality and hashing must preserve the rule that objects which compare equal have equal hashes. Mutability and hashability deserve particular attention when instances are used as dictionary keys or set members.
9. NotImplemented is not False#
A comparison method may return NotImplemented to indicate that it cannot compare the supplied operand pairing. This gives Python an opportunity to apply the relevant alternative dispatch rule.
PYTHONclass Answer: def __eq__(self,other): return NotImplemented a=Answer(); b=Answer() print(a==a,a==b)
Output:
True FalseWhen both applicable equality implementations return NotImplemented, equality falls back to identity. In contrast, unsupported ordering comparisons generally raise TypeError.
Returning False asserts an unequal result. Returning NotImplemented declines to implement that particular comparison. These are different contracts. The related exception NotImplementedError also has a different purpose: it is an exception, not the rich-comparison dispatch sentinel.
User-defined rich comparison methods can return arbitrary objects. When a comparison is used in a condition, Python truth-tests the result. This distinction matters in numerical array libraries, where a comparison may yield an array of elementwise results rather than a single Boolean.
10. Practical example: validate a score range#
PYTHONdef eligible(score): return 0 <= score <= 100 print([eligible(s) for s in (-1,0,100,101)])
Output:
[False, True, True, False]The chained comparison makes both inclusive boundaries explicit. A real input boundary should additionally validate the expected numeric type, whether fractional scores are permitted and how to handle non-finite values.
A valid type and an in-range value are separate requirements. In particular, bool is a subtype of int, so a strict numeric schema may need to reject Boolean values explicitly.
Under a fixed-size scalar cost model, the function uses a bounded number of comparisons and O(1) auxiliary storage.
11. Practical example: sort using explicit comparison keys#
PYTHONitems=[("book",20),("pen",10),("bag",20)] print(sorted(items,key=lambda item:(item[1],item[0])))
Output:
[('pen', 10), ('bag', 20), ('book', 20)]This sorts records first by price, then by name for equal prices. The key function defines the domain ordering explicitly, instead of relying on the original tuple field order.
Python's sorted function is stable: records with equal sort keys preserve their relative input order. It calculates the key once per input item. Under constant-cost key extraction and comparison assumptions, sorting n records takes O(n log n) comparisons in the worst case; the implementation can exploit existing ordered runs. The returned list and sorting workspace require additional storage.
Mixed or partially ordered values should be normalized or mapped to a meaningful common key before sorting.
12. Unsupported comparisons and common mistakes#
The following cases were executed independently and produced TypeError:
| Expression | Reason |
|---|---|
1 < "2" | Integer and string do not have a supported cross-type ordering |
(1+2j) < (2+1j) | Built-in complex numbers do not support ordinary ordering |
{} < {} | Ordinary dictionaries do not support ordering comparisons |
Equality between unrelated built-in types often returns False instead of raising TypeError, but user-defined comparison methods may raise exceptions. Do not assume every comparison between arbitrary types succeeds.
Other common errors include:
- Using = instead of == in a condition.
- Comparing numerical strings lexicographically when numerical ordering is required.
- Assuming comparisons always return a bool.
- Using identity to test ordinary value equality.
- Treating sets as if their subset relationships formed a total ordering.
- Assuming NaN behaves like an ordinary number.
- Implementing custom comparisons without defining a consistent equality and ordering contract.
Frequently asked questions#
What are comparison operators used for?#
They test value relationships and support decisions such as eligibility checks, range validation, equality tests, sorting and filtering.
Does Python allow chained comparisons?#
Yes. A chain such as 1 < x < 10 checks adjacent relationships, evaluates each middle operand at most once, and short-circuits when an earlier comparison fails.
Can different types compare equal?#
Yes. Compatible numeric values such as 1 and 1.0 compare equal. Other cross-type behavior depends on the types and their comparison methods.
Does Python compare strings by length?#
No. Ordinary string ordering is lexicographic by Unicode code points. Length determines the order only when one string is an exact prefix of the other.
Are equality and ordering always supported together?#
No. Complex numbers and ordinary dictionaries are examples of types supporting equality without ordinary ordering.
Interview-ready answer#
Python comparison operators are ==, !=, <, <=, > and >=. They compare values for equality or ordering and normally produce Boolean results for ordinary scalar operands. Python supports chained comparisons such as 0 <= x <= 100, which evaluate middle operands once and short-circuit. Comparison behavior depends on the operand types: strings and compatible sequences compare lexicographically, sets compare through subset relationships, and complex numbers do not support ordinary ordering. Custom classes may implement rich comparison methods. Floating-point precision and NaN require special care, and object identity is distinct from value equality.
Official references#
- Python Language Reference — Comparisons
- Python Standard Library — Comparisons
- Python Language Reference — Basic customization
- Python Standard Library — dataclasses
- Python Standard Library — math.isclose
- Python Tutorial — Floating-Point Arithmetic
- Python Sorting HOWTO
Verification note: Eleven independent code examples matched their documented outputs on CPython 3.13.5, and three expected TypeError cases were confirmed. The Mermaid chain-resolution flowchart was manually reviewed for syntax and evaluation semantics. The local Mermaid parser and CLI were unavailable. Official reference links are supplied under the authorized offline research exception; live documentation, Supabase changelog and public-site rendering were not checked.
References
- 1.Python Language Reference — Comparisonsdocs.python.org
- 2.Python Standard Library — Comparisonsdocs.python.org
- 3.Python Language Reference — Basic customizationdocs.python.org
- 4.Python Standard Library — dataclassesdocs.python.org
- 5.Python Standard Library — math.isclosedocs.python.org
- 6.Python Tutorial — Floating-Point Arithmeticdocs.python.org
- 7.Python Sorting HOWTOdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design