0
0
Pythonprogramming~5 mins

For loop execution model in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: For loop execution model
O(n)
Understanding Time Complexity

When we use a for loop, we want to know how the time it takes grows as we repeat actions.

We ask: How does running the loop more times affect the total work done?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

def print_numbers(n):
    for i in range(n):
        print(i)

This code prints numbers from 0 up to n-1 using a for loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The print statement inside the for loop.
  • How many times: Exactly n times, once for each number from 0 to n-1.
How Execution Grows With Input

As n grows, the number of print actions grows the same way.

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

Pattern observation: The work grows directly in step with n; double n means double work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of loop steps.

Common Mistake

[X] Wrong: "The loop runs instantly no matter how big n is."

[OK] Correct: Each loop step takes some time, so more steps mean more total time.

Interview Connect

Understanding how loops grow helps you explain your code clearly and shows you know how programs scale.

Self-Check

"What if we added a nested for loop inside the first one? How would the time complexity change?"