0
0
Pythonprogramming~5 mins

Instance attributes in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Instance attributes
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Creating Dog objects and accessing their name attribute inside loops.
  • How many times: Both loops run n times, once for each dog.
How Execution Grows With Input

As n grows, the number of Dog objects created and names accessed grows the same way.

Input Size (n)Approx. Operations
10About 20 operations (10 creations + 10 name accesses)
100About 200 operations
1000About 2000 operations

Pattern observation: The total work grows directly with n, doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to create and access instance attributes grows in a straight line as we add more objects.

Common Mistake

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

Interview Connect

Understanding how instance attributes affect time helps you explain object behavior clearly and shows you know how programs scale with data size.

Self-Check

What if we added a nested loop to access attributes multiple times per object? How would the time complexity change?