Methods with return values in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
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?"
Practice
return statement do in Python?Solution
Step 1: Understand the purpose of
Thereturnreturnstatement sends a value back from the method to the caller.Step 2: Differentiate from printing or stopping
Printing shows output but does not send a value back; stopping ends execution.Final Answer:
It sends a value back to where the method was called. -> Option AQuick Check:
Method return = sends value back [OK]
- Confusing return with print
- Thinking return stops the program
- Believing return creates variables
a and b?Solution
Step 1: Identify correct return usage
The method must usereturnto send back the suma + b.Step 2: Check each option
The version withreturn a - breturns the difference. The version withprint(a + b)prints but returnsNone. The version with justa + blacksreturn. Onlydef add(a, b): return a + bcorrectly returns the sum.Final Answer:
def add(a, b): return a + b -> Option CQuick Check:
Return sum = def add(a, b): return a + b [OK]
- Using print instead of return
- Omitting return keyword
- Returning wrong expression
def multiply(x, y):
return x * y
result = multiply(3, 4)
print(result)Solution
Step 1: Understand the method call
The methodmultiplyreturns the product of 3 and 4, which is 12.Step 2: Print the returned value
The variableresultstores 12, soprint(result)outputs 12.Final Answer:
12 -> Option BQuick Check:
3 * 4 = 12 [OK]
- Adding instead of multiplying
- Printing None by missing return
- Confusing string concatenation with multiplication
def greet(name):
print("Hello, " + name)
message = greet("Alice")
print(message)Solution
Step 1: Identify the problem with return value
The method prints but does not return a value, somessageis None.Step 2: Fix by returning the greeting string
Replaceprintwithreturnto send the greeting back.Final Answer:
Changeprinttoreturninside the method. -> Option DQuick Check:
Return greeting to assign message [OK]
- Expecting print to return a value
- Removing needed parameters
- Changing variable names incorrectly
n and values as their squares. Which method below correctly does this?Solution
Step 1: Understand the requirement
The method must return a dictionary with keys 1 to n and values as squares.Step 2: Check each option
The loop buildingresult = {}, settingresult[i] = i * iforiinrange(1, n+1), and returningresultis correct. Returning a list fails. The comprehension{i: i + i for i in range(1, n)}uses doubles instead of squares and misses keyn. Printing without returning fails.Final Answer:
def squares(n): result = {} for i in range(1, n+1): result[i] = i * i return result -> Option AQuick Check:
Return dict with squares = def squares(n): result = {} for i in range(1, n+1): result[i] = i * i return result [OK]
- Returning list instead of dict
- Using wrong range limits
- Printing instead of returning
