Bird
Raised Fist0
Pythonprogramming~20 mins

Comparison magic methods in Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Comparison Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of custom __eq__ method
What is the output of this code?
Python
class Box:
    def __init__(self, volume):
        self.volume = volume
    def __eq__(self, other):
        return self.volume == other.volume

b1 = Box(10)
b2 = Box(10)
b3 = Box(5)

print(b1 == b2)
print(b1 == b3)
AFalse\nTrue
BFalse\nFalse
CTrue\nTrue
DTrue\nFalse
Attempts:
2 left
💡 Hint
The __eq__ method compares the volume attribute of two Box objects.
Predict Output
intermediate
2:00remaining
Output of __lt__ and __gt__ methods
What is the output of this code?
Python
class Number:
    def __init__(self, value):
        self.value = value
    def __lt__(self, other):
        return self.value < other.value
    def __gt__(self, other):
        return self.value > other.value

n1 = Number(3)
n2 = Number(5)
print(n1 < n2)
print(n1 > n2)
ATrue\nFalse
BFalse\nFalse
CTrue\nTrue
DFalse\nTrue
Attempts:
2 left
💡 Hint
The __lt__ method checks if one value is less than the other, __gt__ checks if greater.
Predict Output
advanced
2:00remaining
Output of __le__ and __ge__ with inheritance
What is the output of this code?
Python
class Base:
    def __init__(self, x):
        self.x = x
    def __le__(self, other):
        return self.x <= other.x
    def __ge__(self, other):
        return self.x >= other.x

class Derived(Base):
    pass

b = Base(7)
d = Derived(7)
print(b <= d)
print(b >= d)
ATrue\nTrue
BFalse\nTrue
CTrue\nFalse
DFalse\nFalse
Attempts:
2 left
💡 Hint
Derived inherits comparison methods from Base and both have the same x value.
Predict Output
advanced
2:00remaining
Output of __eq__ with different types
What is the output of this code?
Python
class Item:
    def __init__(self, id):
        self.id = id
    def __eq__(self, other):
        if not isinstance(other, Item):
            return False
        return self.id == other.id

item = Item(10)
print(item == 10)
print(item == Item(10))
ATrue\nTrue
BFalse\nFalse
CFalse\nTrue
DTrue\nFalse
Attempts:
2 left
💡 Hint
The __eq__ method returns False if the other object is not an Item instance.
Predict Output
expert
3:00remaining
Output of chained comparisons with custom __lt__
What is the output of this code?
Python
class Weird:
    def __init__(self, val):
        self.val = val
    def __lt__(self, other):
        print(f"Comparing {self.val} < {other.val}")
        return self.val < other.val

w1 = Weird(1)
w2 = Weird(2)
w3 = Weird(3)
print(w1 < w2 < w3)
AComparing 1 < 2\nComparing 2 < 3\nFalse
BComparing 1 < 2\nComparing 2 < 3\nTrue
CComparing 1 < 2\nTrue
DComparing 1 < 2\nComparing 3 < 2\nTrue
Attempts:
2 left
💡 Hint
Python evaluates chained comparisons by checking each pair separately.

Practice

(1/5)
1. Which magic method in Python is used to define the behavior of the equality operator ==?
easy
A. __eq__
B. __lt__
C. __ne__
D. __gt__

Solution

  1. Step 1: Understand the equality operator

    The == operator checks if two objects are equal.
  2. Step 2: Identify the corresponding magic method

    In Python, __eq__ is the method that defines equality behavior.
  3. Final Answer:

    __eq__ -> Option A
  4. Quick Check:

    Equality operator uses __eq__ [OK]
Hint: Remember: eq means equal, so __eq__ handles == [OK]
Common Mistakes:
  • Confusing __eq__ with __lt__ or __gt__
  • Thinking __ne__ handles equality
  • Mixing up method names with comparison operators
2. Which of the following is the correct syntax to define the less than operator < in a Python class?
easy
A. def __lt__(self):
B. def __less_than__(self, other):
C. def __less__(self, other):
D. def __lt__(self, other):

Solution

  1. Step 1: Recall the magic method name for <

    The method for < is __lt__ and it takes two parameters: self and other.
  2. Step 2: Check method signature correctness

    Correct syntax is def __lt__(self, other):. Other options have wrong names or missing parameters.
  3. Final Answer:

    def __lt__(self, other): -> Option D
  4. Quick Check:

    Less than operator uses __lt__(self, other) [OK]
Hint: Magic methods for comparisons always take self and other [OK]
Common Mistakes:
  • Using wrong method names like __less_than__
  • Omitting the other parameter
  • Using incorrect method signatures
3. What will be the output of the following code?
class Number:
    def __init__(self, value):
        self.value = value
    def __gt__(self, other):
        return self.value > other.value

n1 = Number(5)
n2 = Number(3)
print(n1 > n2)
medium
A. False
B. TypeError
C. True
D. None

Solution

  1. Step 1: Understand the __gt__ method

    The __gt__ method compares self.value and other.value.
  2. Step 2: Evaluate the comparison

    n1.value is 5 and n2.value is 3, so 5 > 3 is True.
  3. Final Answer:

    True -> Option C
  4. Quick Check:

    5 > 3 = True [OK]
Hint: Check the values inside objects when comparing [OK]
Common Mistakes:
  • Forgetting to compare attributes inside objects
  • Expecting print to show object addresses
  • Confusing __gt__ with __lt__
4. Identify the error in the following class that tries to implement the not equal operator !=:
class Item:
    def __init__(self, val):
        self.val = val
    def __ne__(self):
        return self.val != other.val
medium
A. The class should inherit from object explicitly
B. __ne__ method is missing the other parameter
C. The __ne__ method should return True always
D. The __init__ method is missing self

Solution

  1. Step 1: Check __ne__ method signature

    The __ne__ method must take two parameters: self and other.
  2. Step 2: Identify missing parameter

    Here, other is used but not declared as a parameter, causing an error.
  3. Final Answer:

    __ne__ method is missing the other parameter -> Option B
  4. Quick Check:

    __ne__ needs (self, other) parameters [OK]
Hint: Comparison methods always take self and other [OK]
Common Mistakes:
  • Omitting the other parameter in comparison methods
  • Misunderstanding method signatures
  • Thinking inheritance from object is required in Python 3
5. You want to create a class Box where two boxes are considered equal if their volumes are equal. Which magic method should you implement and how?
class Box:
    def __init__(self, length, width, height):
        self.length = length
        self.width = width
        self.height = height
    # Your code here
hard
A. Implement __eq__(self, other) to compare volumes: return self.length * self.width * self.height == other.length * other.width * other.height
B. Implement __lt__(self, other) to compare volumes
C. Implement __ne__(self, other) to compare volumes
D. Implement __gt__(self, other) to compare volumes

Solution

  1. Step 1: Identify the comparison needed

    Equality means using ==, so implement __eq__.
  2. Step 2: Define volume comparison inside __eq__

    Calculate volume for both boxes and compare for equality.
  3. Final Answer:

    Implement __eq__(self, other) to compare volumes: return self.length * self.width * self.height == other.length * other.width * other.height -> Option A
  4. Quick Check:

    Equality uses __eq__ comparing volumes [OK]
Hint: Use __eq__ to define equality based on volume [OK]
Common Mistakes:
  • Using __lt__ or __gt__ for equality
  • Not comparing volumes but attributes directly
  • Forgetting to implement __eq__ for == operator