Multiple return values in Python - Time & Space Complexity
We want to see how the time a function takes changes when it returns more than one value.
Does returning multiple values make the function slower as input grows?
Analyze the time complexity of the following code snippet.
def min_max(numbers):
minimum = numbers[0]
maximum = numbers[0]
for num in numbers:
if num < minimum:
minimum = num
elif num > maximum:
maximum = num
return minimum, maximum
This function finds the smallest and largest numbers in a list and returns both.
- Primary operation: One loop through the list of numbers.
- How many times: Once for each number in the list.
As the list gets bigger, the function checks each number once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line with the input size.
[X] Wrong: "Returning two values makes the function twice as slow."
[OK] Correct: Returning multiple values just packages results together; it does not add extra loops or checks.
Understanding how returning multiple values affects time helps you explain your code clearly and confidently in interviews.
"What if the function returned the minimum, maximum, and the average? How would the time complexity change?"