Comparison magic methods in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
We want to understand how fast comparison magic methods run when comparing objects.
How does the time to compare grow as the objects get bigger or more complex?
Analyze the time complexity of the following code snippet.
class Box:
def __init__(self, items):
self.items = items
def __eq__(self, other):
return self.items == other.items
This code defines a class with a comparison method that checks if two boxes have the same items.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Comparing the lists inside the boxes element by element.
- How many times: Once for each item in the list until a difference is found or all items are checked.
As the number of items in the boxes grows, the comparison takes longer because it checks each item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 item comparisons |
| 100 | About 100 item comparisons |
| 1000 | About 1000 item comparisons |
Pattern observation: The work grows roughly in direct proportion to the number of items.
Time Complexity: O(n)
This means the time to compare grows linearly with the number of items in the boxes.
[X] Wrong: "Comparing two objects always takes the same time no matter their size."
[OK] Correct: The comparison checks each item inside, so bigger objects take more time.
Knowing how comparison methods scale helps you write efficient code and explain your choices clearly.
"What if the items were stored in a set instead of a list? How would the time complexity change?"
Practice
==?Solution
Step 1: Understand the equality operator
The==operator checks if two objects are equal.Step 2: Identify the corresponding magic method
In Python,__eq__is the method that defines equality behavior.Final Answer:
__eq__ -> Option AQuick Check:
Equality operator uses __eq__ [OK]
- Confusing __eq__ with __lt__ or __gt__
- Thinking __ne__ handles equality
- Mixing up method names with comparison operators
< in a Python class?Solution
Step 1: Recall the magic method name for <
The method for < is__lt__and it takes two parameters: self and other.Step 2: Check method signature correctness
Correct syntax isdef __lt__(self, other):. Other options have wrong names or missing parameters.Final Answer:
def __lt__(self, other): -> Option DQuick Check:
Less than operator uses __lt__(self, other) [OK]
- Using wrong method names like __less_than__
- Omitting the other parameter
- Using incorrect method signatures
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)Solution
Step 1: Understand the __gt__ method
The__gt__method comparesself.valueandother.value.Step 2: Evaluate the comparison
n1.value is 5 and n2.value is 3, so 5 > 3 is True.Final Answer:
True -> Option CQuick Check:
5 > 3 = True [OK]
- Forgetting to compare attributes inside objects
- Expecting print to show object addresses
- Confusing __gt__ with __lt__
!=:
class Item:
def __init__(self, val):
self.val = val
def __ne__(self):
return self.val != other.valSolution
Step 1: Check __ne__ method signature
The__ne__method must take two parameters: self and other.Step 2: Identify missing parameter
Here,otheris used but not declared as a parameter, causing an error.Final Answer:
__ne__ method is missing the other parameter -> Option BQuick Check:
__ne__ needs (self, other) parameters [OK]
- Omitting the other parameter in comparison methods
- Misunderstanding method signatures
- Thinking inheritance from object is required in Python 3
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 hereSolution
Step 1: Identify the comparison needed
Equality means using==, so implement__eq__.Step 2: Define volume comparison inside __eq__
Calculate volume for both boxes and compare for equality.Final Answer:
Implement __eq__(self, other) to compare volumes: return self.length * self.width * self.height == other.length * other.width * other.height -> Option AQuick Check:
Equality uses __eq__ comparing volumes [OK]
- Using __lt__ or __gt__ for equality
- Not comparing volumes but attributes directly
- Forgetting to implement __eq__ for == operator
