Accessing and modifying attributes in Python - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: Accessing and modifying the
nameattribute of the object. - How many times: 1000 times inside the loop.
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 |
|---|---|
| 10 | 20 attribute actions (10 sets + 10 gets) |
| 100 | 200 attribute actions |
| 1000 | 2000 attribute actions |
Pattern observation: The total work grows directly with the number of loop steps.
Time Complexity: O(n)
This means the time needed grows in a straight line as we do more attribute accesses and changes.
[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.
Understanding how attribute access scales helps you explain how your code handles data efficiently, a useful skill in many programming tasks.
"What if we added a loop inside the attribute setter that searched a list each time? How would the time complexity change?"