Methods with return values in Python - Time & Space 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.
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 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.
As the list gets longer, the method takes longer because it adds each number one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The time grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to get the return value grows in a straight line with the input size.
[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.
Understanding how methods with return values scale helps you explain your code clearly and shows you know how to write efficient programs.
"What if the method used recursion instead of a loop? How would the time complexity change?"