Purpose of constructors in Python - Time & Space Complexity
We want to understand how the time it takes to create objects grows as we create more of them.
How does the constructor's work change when we make many objects?
Analyze the time complexity of the following code snippet.
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
cars = []
n = 10
for i in range(n):
cars.append(Car('Toyota', 'Corolla'))
This code creates a list of n car objects, each initialized with the same make and model.
- Primary operation: Calling the constructor
Car()inside the loop. - How many times: Exactly
ntimes, once for each object created.
Each new object requires the constructor to run once, so the total work grows directly with the number of objects.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 constructor calls |
| 100 | 100 constructor calls |
| 1000 | 1000 constructor calls |
Pattern observation: The work grows in a straight line as we add more objects.
Time Complexity: O(n)
This means the time to create all objects grows directly in proportion to how many objects we make.
[X] Wrong: "Creating many objects is always instant and does not depend on how many we make."
[OK] Correct: Each object needs its constructor to run, so more objects mean more work and more time.
Understanding how constructors affect time helps you explain how object creation scales in programs, a useful skill when designing efficient code.
"What if the constructor did a complex calculation inside? How would that change the time complexity?"