Assignment and augmented assignment in Python - Time & Space Complexity
Let's see how the time it takes to run code with assignment and augmented assignment changes as we work with bigger numbers.
We want to know how the number of steps grows when we do simple assignments or add-and-assign repeatedly.
Analyze the time complexity of the following code snippet.
total = 0
for i in range(n):
total += i
This code adds numbers from 0 up to n-1 into a total using augmented assignment.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The addition and assignment inside the loop (total += i).
- How many times: This happens once for each number from 0 to n-1, so n times.
Each time we increase n, the loop runs more times, doing one addition and assignment each time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions and assignments |
| 100 | 100 additions and assignments |
| 1000 | 1000 additions and assignments |
Pattern observation: The number of steps grows directly with n; if n doubles, the work doubles.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the size of n.
[X] Wrong: "Augmented assignment like total += i is faster and takes constant time regardless of n."
[OK] Correct: Even though augmented assignment looks simple, it happens inside a loop that runs n times, so total steps grow with n.
Understanding how simple loops with assignments grow helps you explain how programs handle bigger data smoothly and clearly.
"What if we replaced the loop with a single assignment like total = n * (n - 1) // 2? How would the time complexity change?"