Comparisons in Python

Comparisons let your code answer questions—“Is this value equal to that one?” or “Does this number fall within a given range?” By yielding True or False, comparison expressions drive conditional logic, filtering, sorting, and data validation. In this guide, we’ll explore Python’s comparison operators, see how they work on various types, cover chaining and best practices, and finish with a mini project that filters data using comparisons.


Comparison Operators Overview

Python offers six relational operators that compare two values and return a Boolean:

OperatorMeaning
<Less than
<=Less than or equal to
>Greater than
>=Greater than or equal to
==Equal to
!=Not equal to

Use these operators with numbers, strings, and sequence types to test ordering or equality.


Equality and Inequality

The == and != operators check whether two objects have the same value:

print(5 == 5)        # True
print("apple" == "Apple")  # False (case-sensitive)
print([1,2,3] != [1,2])    # True
  • == returns True if operands are equal.
  • != returns True if operands differ.

Equality on containers (lists, tuples) does a deep element-by-element comparison.


Ordering Comparisons

Use <, <=, >, and >= to test relative order:

print(3 < 7)        # True
print(7 >= 7)       # True
print("cat" > "car")  # True ('t' comes after 'r')
  • Numeric comparisons follow arithmetic rules.
  • String comparisons use lexicographic order (character by character).
  • Sequences like tuples compare element-wise until a difference appears.

Chained Comparisons

Python lets you combine comparisons succinctly without repeating the middle operand:

x = 5
print(1 < x < 10)      # True
print(0 <= x <= 5)     # True

This is equivalent to:

print((1 < x) and (x < 10))

Chaining improves readability and avoids redundant code.


Comparing Mixed and Custom Types

  • Mixed numeric types (int vs. float) auto-promote to float: print(3 == 3.0) # True
  • Complex numbers don’t support < or > but can be compared for equality: a, b = 1+2j, 2+3j print(a == b) # False # print(a < b) # TypeError
  • Custom classes can define comparison behavior by implementing magic methods like __eq__, __lt__, etc.

Common Pitfalls

  • Floating-point precision: x = 0.1 + 0.2 print(x == 0.3) # False # Use a tolerance print(abs(x - 0.3) < 1e-9) # True
  • Unintended type comparisons can quietly return False rather than error: print(5 == "5") # False
  • Dictionary comparisons allow only == and !=, not ordering operators.

Mini Project: Range Filter Utility

Build a function to filter a list of numbers, returning only those within a specified inclusive range.

def filter_in_range(numbers, low, high):
    """
    Return all values x in `numbers` such that low <= x <= high.
    """
    return [x for x in numbers if low <= x <= high]

# Example usage
data = [3, 7, 10, 15, 20, 25]
print(filter_in_range(data, 10, 20))
# Output: [10, 15, 20]

This project demonstrates:

  • Using <= and >= for boundary checks
  • A chained comparison low <= x <= high for clarity
  • List comprehensions driven by comparison expressions

Conclusion

Comparisons are the foundation of decision-making in Python. By mastering:

  • Equality (==, !=)
  • Ordering (<, <=, >, >=)
  • Chaining operators for concise range checks
  • Awareness of type-specific behaviors and pitfalls

you’ll write code that validates input, filters data, and adapts its flow based on dynamic conditions. Keep experimenting with comparisons to harness their full power in your programs.


Discover more from Affordable Tutor

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top