0
0
Pythonprogramming~5 mins

Adding custom attributes in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Adding custom attributes
O(n)
Understanding Time Complexity

When we add custom attributes to objects, it is important to know how the time to do this grows as we add more attributes.

We want to understand how the work changes when the number of attributes increases.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

class MyObject:
    pass

obj = MyObject()

for i in range(n):
    setattr(obj, f'attr{i}', i)

This code adds n custom attributes to an object one by one using a loop.

Identify Repeating Operations
  • Primary operation: Adding one attribute to the object using setattr.
  • How many times: This operation repeats n times, once for each attribute.
How Execution Grows With Input

Each new attribute is added one after another, so the total work grows as we add more attributes.

Input Size (n)Approx. Operations
1010 attribute additions
100100 attribute additions
10001000 attribute additions

Pattern observation: The work grows directly in proportion to the number of attributes added.

Final Time Complexity

Time Complexity: O(n)

This means the time to add attributes grows linearly with the number of attributes you add.

Common Mistake

[X] Wrong: "Adding many attributes is always instant and does not depend on how many there are."

[OK] Correct: Each attribute addition takes some time, so more attributes mean more total time.

Interview Connect

Understanding how adding properties to objects scales helps you reason about performance in real programs where objects grow dynamically.

Self-Check

"What if we added all attributes at once using a dictionary update instead of one by one? How would the time complexity change?"