Instance attributes in Python - Time & Space Complexity
Let's see how the time to run code changes when we use instance attributes in Python.
We want to know how accessing or setting these attributes affects the program's speed as we work with more objects.
Analyze the time complexity of the following code snippet.
class Dog:
def __init__(self, name):
self.name = name
dogs = []
n = 10 # Added definition for n
for i in range(n):
dogs.append(Dog(f"Dog{i}"))
for dog in dogs:
print(dog.name)
This code creates n Dog objects, each with a name stored as an instance attribute, then prints each dog's name.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating Dog objects and accessing their
nameattribute inside loops. - How many times: Both loops run n times, once for each dog.
As n grows, the number of Dog objects created and names accessed grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 operations (10 creations + 10 name accesses) |
| 100 | About 200 operations |
| 1000 | About 2000 operations |
Pattern observation: The total work grows directly with n, doubling n doubles the work.
Time Complexity: O(n)
This means the time to create and access instance attributes grows in a straight line as we add more objects.
[X] Wrong: "Accessing instance attributes inside a loop is constant time no matter how many objects there are."
[OK] Correct: While each attribute access is quick, doing it for many objects adds up, so total time grows with the number of objects.
Understanding how instance attributes affect time helps you explain object behavior clearly and shows you know how programs scale with data size.
What if we added a nested loop to access attributes multiple times per object? How would the time complexity change?