Default values in constructors in Python - Time & Space Complexity
When we use default values in constructors, we want to know how this choice affects the time it takes to create objects.
We ask: Does setting default values change how long the constructor runs as we create more objects?
Analyze the time complexity of the following code snippet.
class Box:
def __init__(self, length=1, width=1, height=1):
self.length = length
self.width = width
self.height = height
boxes = []
n = 10 # Example value for n
for i in range(n):
boxes.append(Box())
This code creates n Box objects using default values in the constructor.
- Primary operation: The loop that creates and adds Box objects to the list.
- How many times: The loop runs n times, once for each Box created.
Each new object takes a small, fixed amount of time to create because the constructor just sets three values.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 simple assignments |
| 100 | About 300 simple assignments |
| 1000 | About 3000 simple assignments |
Pattern observation: The total work grows directly with the number of objects created.
Time Complexity: O(n)
This means the time to create n objects grows in a straight line with n.
[X] Wrong: "Using default values makes the constructor run faster or slower depending on n."
[OK] Correct: The default values are set once per object and do not add extra loops or complex steps, so the time per object stays the same regardless of defaults.
Understanding how constructors work with default values helps you explain object creation clearly and shows you can think about how code scales.
"What if the constructor included a loop that ran based on one of the input values? How would the time complexity change?"