0
0
Pythonprogramming~5 mins

Assignment and augmented assignment in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Assignment and augmented assignment
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each time we increase n, the loop runs more times, doing one addition and assignment each time.

Input Size (n)Approx. Operations
1010 additions and assignments
100100 additions and assignments
10001000 additions and assignments

Pattern observation: The number of steps grows directly with n; if n doubles, the work doubles.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the size of n.

Common Mistake

[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.

Interview Connect

Understanding how simple loops with assignments grow helps you explain how programs handle bigger data smoothly and clearly.

Self-Check

"What if we replaced the loop with a single assignment like total = n * (n - 1) // 2? How would the time complexity change?"