0
0
Pythonprogramming~5 mins

Formatting using format() method in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Formatting using format() method
O(n^2)
Understanding Time Complexity

Let's see how the time it takes to format strings using the format() method changes as we add more items to format.

We want to know how the work grows when formatting many values in one string.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

def format_numbers(numbers):
    result = ""
    for num in numbers:
        result += "Number: {}\n".format(num)
    return result

This code takes a list of numbers and creates a string with each number formatted on its own line.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each number and formatting it with format().
  • How many times: Once for every number in the input list.
How Execution Grows With Input

As the list gets bigger, the code formats more numbers, so the work grows steadily.

Input Size (n)Approx. Operations
10About 10 formatting steps
100About 100 formatting steps
1000About 1000 formatting steps

Pattern observation: The work grows directly with the number of items; double the items, double the work.

Final Time Complexity

Time Complexity: O(n^2)

This means the time to format grows quadratically with the number of items you format, due to repeated string concatenation.

Common Mistake

[X] Wrong: "Formatting a string with format() is always constant time, so the whole function is constant time."

[OK] Correct: Each call to format() happens once per item, and string concatenation inside a loop causes the total time to grow quadratically.

Interview Connect

Understanding how string formatting scales helps you write efficient code when working with many values, a useful skill in many programming tasks.

Self-Check

"What if we used a list comprehension and join() instead of adding strings inside the loop? How would the time complexity change?"