For–else execution behavior in Python - Time & Space Complexity
We want to understand how the time taken by a for-else structure changes as the input grows.
Specifically, how the loop and else parts affect the total steps done.
Analyze the time complexity of the following code snippet.
def find_target(numbers, target):
for num in numbers:
if num == target:
break
else:
print("Target not found")
This code looks for a target number in a list and prints a message if it is not found.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of numbers.
- How many times: Up to once for each number until the target is found or the list ends.
As the list gets longer, the loop may run more times if the target is not found early.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of steps grows roughly in direct proportion to the list size if the target is not found early.
Time Complexity: O(n)
This means the time grows linearly with the number of items to check.
[X] Wrong: "The else part runs every time and adds extra time."
[OK] Correct: The else only runs if the loop finishes without break, so it does not add repeated work inside the loop.
Understanding how for-else works helps you explain loop behavior clearly and shows you know Python's special features.
"What if we replaced the break with a return statement inside the loop? How would the time complexity change?"