0
0
Pythonprogramming~5 mins

Methods with return values in Python - Time & Space Complexity

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

When we use methods that return values, it is important to see how long they take to run as the input grows.

We want to know how the time to get the return value changes when the input gets bigger.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

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

result = sum_list([1, 2, 3, 4, 5])
print(result)

This method adds up all numbers in a list and returns the total sum.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each number in the list once.
  • How many times: Exactly once for each item in the input list.
How Execution Grows With Input

As the list gets longer, the method takes longer because it adds each number one by one.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 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 get the return value grows in a straight line with the input size.

Common Mistake

[X] Wrong: "Since the method just returns a value, it must be very fast no matter the input size."

[OK] Correct: The method still does work inside, like looping through the list, so bigger inputs take more time.

Interview Connect

Understanding how methods with return values scale helps you explain your code clearly and shows you know how to write efficient programs.

Self-Check

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