0
0
Pythonprogramming~5 mins

Instance methods in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Instance methods
O(n)
Understanding Time Complexity

When we use instance methods in Python, we want to know how the time it takes to run changes as the input grows.

We ask: How does calling an instance method affect the program's speed when the input size changes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Counter:
    def __init__(self, numbers):
        self.numbers = numbers

    def total(self):
        total = 0
        for num in self.numbers:
            total += num
        return total

c = Counter([1, 2, 3, 4, 5])
print(c.total())
    

This code defines a class with an instance method that adds up all numbers in a list.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the list of numbers inside the total method.
  • How many times: Once for each number in the list.
How Execution Grows With Input

As the list gets longer, the method has to add more numbers, so it takes more time.

Input Size (n)Approx. Operations
10About 10 additions
100About 100 additions
1000About 1000 additions

Pattern observation: The time grows directly with the number of items; double the items, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the method grows in a straight line with the size of the list.

Common Mistake

[X] Wrong: "Calling an instance method always takes the same time no matter the input size."

[OK] Correct: The method's work depends on the data it processes. If it loops over a list, more items mean more work and more time.

Interview Connect

Understanding how instance methods scale with input helps you explain your code's efficiency clearly and confidently in real projects and interviews.

Self-Check

"What if the total method used recursion instead of a loop? How would the time complexity change?"