0
0
Pythonprogramming~5 mins

Local scope in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Local scope
O(n)
Understanding Time Complexity

When we talk about local scope in Python, we want to see how fast the program runs when it uses variables inside functions.

We ask: How does the time to run change as the function does more work?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

def greet(names):
    for name in names:
        message = f"Hello, {name}!"
        print(message)

names_list = ["Alice", "Bob", "Charlie"]
greet(names_list)

This code says hello to each name in a list by creating a message inside the function and printing it.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that goes through each name in the list.
  • How many times: Once for each name in the input list.
How Execution Grows With Input

As the list of names gets bigger, the program says hello more times, so it takes more steps.

Input Size (n)Approx. Operations
10About 10 greetings and prints
100About 100 greetings and prints
1000About 1000 greetings and prints

Pattern observation: The work grows evenly as the list grows; double the names, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly with the number of names we greet.

Common Mistake

[X] Wrong: "Because the message is created inside the function, it makes the code slower in a big way."

[OK] Correct: Creating a message inside the loop is quick and happens once per name, so it doesn't add extra loops or big delays.

Interview Connect

Understanding how local variables inside functions affect speed helps you explain your code clearly and shows you know how programs grow with input size.

Self-Check

"What if we added another loop inside the function to say hello twice to each name? How would the time complexity change?"