Variable assignment in Python - Time & Space Complexity
Let's see how fast variable assignment happens in Python.
We want to know how the time to assign a value changes as we assign more variables.
Analyze the time complexity of the following code snippet.
for i in range(n):
x = i
This code assigns the value of i to x repeatedly in a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Variable assignment
x = iinside the loop. - How many times: Exactly
ntimes, once per loop cycle.
Each time we increase n, the number of assignments grows the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 assignments |
| 100 | 100 assignments |
| 1000 | 1000 assignments |
Pattern observation: The number of assignments grows directly with n.
Time Complexity: O(n)
This means the time to finish grows in a straight line as you assign more variables.
[X] Wrong: "Variable assignment is always instant and does not depend on how many times it runs."
[OK] Correct: While one assignment is very fast, doing it many times adds up, so total time grows with the number of assignments.
Understanding how simple steps add up helps you explain code speed clearly and confidently.
"What if we assigned a list of size n to x inside the loop? How would the time complexity change?"