Classes and objects in Python - Time & Space Complexity
When we use classes and objects, we want to know how long it takes to create and use them as our program grows.
We ask: How does the time to run change when we make more objects or call methods many times?
Analyze the time complexity of the following code snippet.
class Counter:
def __init__(self, start=0):
self.count = start
def increment(self):
self.count += 1
n = 10 # Example value for n
counters = [Counter() for _ in range(n)]
for counter in counters:
counter.increment()
This code creates a list of n Counter objects and then calls the increment method on each one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating n objects and calling increment n times.
- How many times: Each operation happens once per object, so n times.
As we increase n, the number of objects and method calls grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 (10 creations + 10 increments) |
| 100 | About 200 (100 creations + 100 increments) |
| 1000 | About 2000 (1000 creations + 1000 increments) |
Pattern observation: The total work grows evenly as n grows; doubling n doubles the work.
Time Complexity: O(n)
This means the time to create and update all objects grows in a straight line with the number of objects.
[X] Wrong: "Creating many objects is instant and does not affect time."
[OK] Correct: Each object takes time to create and use, so more objects mean more total time.
Understanding how object creation and method calls scale helps you explain program speed clearly and confidently.
"What if the increment method had a loop inside that runs m times? How would the time complexity change?"