Parameters and arguments in Python - Time & Space Complexity
When we use parameters and arguments in functions, we want to know how the time to run the function changes as the input changes.
We ask: How does the function's work grow when the input values get bigger or more complex?
Analyze the time complexity of the following code snippet.
def greet(names):
for name in names:
print(f"Hello, {name}!")
user_list = ["Alice", "Bob", "Charlie"]
greet(user_list)
This code defines a function that greets each name in a list by printing a message.
- Primary operation: Looping through each name in the list.
- How many times: Once for each name in the input list.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 greetings printed |
| 100 | About 100 greetings printed |
| 1000 | About 1000 greetings printed |
Pattern observation: The work grows directly with the number of names. Double the names, double the greetings.
Time Complexity: O(n)
This means the time to run the function grows in a straight line with the number of input names.
[X] Wrong: "The function always takes the same time no matter how many names there are."
[OK] Correct: The function does one action for each name, so more names mean more work and more time.
Understanding how function inputs affect running time helps you explain your code clearly and shows you know how programs behave with different data sizes.
"What if the function called another function inside the loop that also loops over the input list? How would the time complexity change?"