0
0
Pythonprogramming~5 mins

Variable assignment in Python - Time & Space Complexity

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

Scenario Under Consideration

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

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Variable assignment x = i inside the loop.
  • How many times: Exactly n times, once per loop cycle.
How Execution Grows With Input

Each time we increase n, the number of assignments grows the same amount.

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

Pattern observation: The number of assignments grows directly with n.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as you assign more variables.

Common Mistake

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

Interview Connect

Understanding how simple steps add up helps you explain code speed clearly and confidently.

Self-Check

"What if we assigned a list of size n to x inside the loop? How would the time complexity change?"