0
0
Pythonprogramming~5 mins

Default arguments in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Default arguments
O(times)
Understanding Time Complexity

When using default arguments in functions, it's important to see how they affect the work done each time the function runs.

We want to know if having default values changes how long the function takes as input grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

def greet(name, times=1):
    for _ in range(times):
        print(f"Hello, {name}!")

# Calling the function
# greet("Alice")  # uses default times=1
# greet("Bob", 3) # times=3

This function prints a greeting message a number of times, using a default value if no number is given.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that prints the greeting.
  • How many times: It runs exactly times times, which can be the default or a given number.
How Execution Grows With Input

Each time the function runs, the number of print operations grows with the times value.

Input Size (times)Approx. Operations
11 print
1010 prints
100100 prints

Pattern observation: The work grows directly with the number of times the loop runs.

Final Time Complexity

Time Complexity: O(times)

This means the time taken grows in a straight line with how many times we want to print the greeting.

Common Mistake

[X] Wrong: "Using default arguments makes the function run faster or slower depending on the default value."

[OK] Correct: The default value just sets a starting number; the function's time depends on the actual number used when called, not on whether it was default or given.

Interview Connect

Understanding how default arguments affect loops helps you explain how your code behaves with different inputs, a skill that shows clear thinking in interviews.

Self-Check

"What if the function called another function inside the loop? How would that change the time complexity?"