Why scope matters in Python - Performance Analysis
When we write code, where variables live and how long they last can affect how many times parts of the code run.
We want to see how the place where variables are kept (scope) changes the work the program does.
Analyze the time complexity of the following code snippet.
def count_items(items):
total = 0
for item in items:
count = 0
for char in item:
count += 1
total += count
return total
This code counts the total number of characters in a list of strings, resetting the count inside the outer loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops - outer loop over items, inner loop over characters in each item.
- How many times: Outer loop runs once per item; inner loop runs once per character in each item.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 items (avg 5 chars) | About 50 character checks |
| 100 items (avg 5 chars) | About 500 character checks |
| 1000 items (avg 5 chars) | About 5000 character checks |
Pattern observation: The total work grows roughly with the total number of characters across all items.
Time Complexity: O(n * m)
This means the time grows with the number of items times the average length of each item.
[X] Wrong: "Since the count variable resets inside the loop, it makes the code faster or slower overall."
[OK] Correct: Resetting the count inside the loop does not change how many times the inner loop runs; it only affects where the count is stored, not the total work done.
Understanding how variable placement affects repeated work helps you write clearer and more efficient code, a skill valued in many coding challenges and real projects.
What if we moved the count variable outside the outer loop and updated it differently? How would the time complexity change?