0
0
Pythonprogramming~5 mins

Default values in constructors in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Default values in constructors
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • 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.
How Execution Grows With Input

Each new object takes a small, fixed amount of time to create because the constructor just sets three values.

Input Size (n)Approx. Operations
10About 30 simple assignments
100About 300 simple assignments
1000About 3000 simple assignments

Pattern observation: The total work grows directly with the number of objects created.

Final Time Complexity

Time Complexity: O(n)

This means the time to create n objects grows in a straight line with n.

Common Mistake

[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.

Interview Connect

Understanding how constructors work with default values helps you explain object creation clearly and shows you can think about how code scales.

Self-Check

"What if the constructor included a loop that ran based on one of the input values? How would the time complexity change?"