Why operators are needed in Python - Performance Analysis
Operators help us perform actions like adding or comparing values in code.
We want to see how the time to do these actions changes as the input size grows.
Analyze the time complexity of the following code snippet.
numbers = [1, 2, 3, 4, 5]
sum_total = 0
for num in numbers:
sum_total += num
print(sum_total)
This code adds up all numbers in a list using the addition operator inside a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Addition operator used inside the loop.
- How many times: Once for each number in the list.
As the list gets bigger, the number of additions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to add all numbers grows in a straight line as the list gets bigger.
[X] Wrong: "Operators like addition take the same time no matter how many numbers we add."
[OK] Correct: Each addition happens once per number, so more numbers mean more additions and more time.
Understanding how operators inside loops affect time helps you explain how your code scales with data size.
"What if we used multiplication instead of addition inside the loop? How would the time complexity change?"