Local scope in Python - Time & Space 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?
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 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.
As the list of names gets bigger, the program says hello more times, so it takes more steps.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 greetings and prints |
| 100 | About 100 greetings and prints |
| 1000 | About 1000 greetings and prints |
Pattern observation: The work grows evenly as the list grows; double the names, double the work.
Time Complexity: O(n)
This means the time to run grows directly with the number of names we greet.
[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.
Understanding how local variables inside functions affect speed helps you explain your code clearly and shows you know how programs grow with input size.
"What if we added another loop inside the function to say hello twice to each name? How would the time complexity change?"