0
0
Pythonprogramming~5 mins

Methods with parameters in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Methods with parameters
O(n)
Understanding Time Complexity

When we use methods with parameters, we want to know how the time it takes to run changes as the input changes.

We ask: How does the method's work grow when the input values get bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Calculator:
    def multiply(self, numbers):
        result = 1
        for num in numbers:
            result *= num
        return result

calc = Calculator()
print(calc.multiply([2, 3, 4, 5]))

This method multiplies all numbers in a list and returns the product.

Identify Repeating Operations
  • Primary operation: Looping through each number in the input list.
  • How many times: Once for every number in the list.
How Execution Grows With Input

As the list gets longer, the method does more multiplications, one for each number.

Input Size (n)Approx. Operations
1010 multiplications
100100 multiplications
10001000 multiplications

Pattern observation: The work grows directly with the size of the input list.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the input list gets bigger.

Common Mistake

[X] Wrong: "The method takes the same time no matter how many numbers are in the list."

[OK] Correct: Because the method must multiply each number, more numbers mean more work and more time.

Interview Connect

Understanding how methods with parameters scale helps you explain your code clearly and shows you know how input size affects performance.

Self-Check

"What if the method also called another method inside the loop? How would the time complexity change?"