0
0
Pythonprogramming~5 mins

Accessing and modifying attributes in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Accessing and modifying attributes
O(n)
Understanding Time Complexity

When we access or change attributes in Python objects, it is important to know how the time needed grows as we do more operations.

We want to understand how fast or slow these attribute actions happen as the program runs.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Person:
    def __init__(self, name):
        self.name = name

p = Person("Alice")
for i in range(1000):
    p.name = f"Name{i}"
    current_name = p.name

This code creates a person and then changes and reads the name attribute 1000 times in a loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Accessing and modifying the name attribute of the object.
  • How many times: 1000 times inside the loop.
How Execution Grows With Input

Each loop step does a simple attribute change and access, which takes about the same time no matter how many times we do it.

Input Size (n)Approx. Operations
1020 attribute actions (10 sets + 10 gets)
100200 attribute actions
10002000 attribute actions

Pattern observation: The total work grows directly with the number of loop steps.

Final Time Complexity

Time Complexity: O(n)

This means the time needed grows in a straight line as we do more attribute accesses and changes.

Common Mistake

[X] Wrong: "Accessing or changing an attribute takes longer each time because the object gets bigger."

[OK] Correct: Attribute access and modification in Python objects happen in constant time, so the object size does not slow down these operations.

Interview Connect

Understanding how attribute access scales helps you explain how your code handles data efficiently, a useful skill in many programming tasks.

Self-Check

"What if we added a loop inside the attribute setter that searched a list each time? How would the time complexity change?"