0
0
Pythonprogramming~5 mins

Parameters and arguments in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Parameters and arguments
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: Looping through each name in the list.
  • How many times: Once for each name in the input list.
How Execution Grows With Input

Explain the growth pattern intuitively.

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

Pattern observation: The work grows directly with the number of names. Double the names, double the greetings.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the function grows in a straight line with the number of input names.

Common Mistake

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

Interview Connect

Understanding how function inputs affect running time helps you explain your code clearly and shows you know how programs behave with different data sizes.

Self-Check

"What if the function called another function inside the loop that also loops over the input list? How would the time complexity change?"