Constructor parameters in Python - Time & Space Complexity
Let's see how the time it takes to create an object changes when we pass different parameters to its constructor.
We want to know: does adding more or bigger parameters make creating the object slower?
Analyze the time complexity of the following code snippet.
class Box:
def __init__(self, items):
self.contents = []
for item in items:
self.contents.append(item)
box = Box([1, 2, 3, 4, 5])
This code creates a Box object and copies each item from the input list into the box's contents.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that goes through each item in the input list.
- How many times: Once for every item in the input list.
As the number of items increases, the loop runs more times, copying each item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 copies |
| 100 | About 100 copies |
| 1000 | About 1000 copies |
Pattern observation: The work grows directly with the number of items; double the items, double the work.
Time Complexity: O(n)
This means the time to create the object grows in a straight line with the number of items passed in.
[X] Wrong: "Constructor parameters don't affect how long object creation takes."
[OK] Correct: If the constructor processes each parameter, more or bigger parameters mean more work and more time.
Understanding how constructor parameters affect time helps you explain object creation costs clearly and confidently in real projects.
What if the constructor used a built-in copy method instead of a loop? How would the time complexity change?