Formatting using format() method in Python - Time & Space 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.
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 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.
As the list gets bigger, the code formats more numbers, so the work grows steadily.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 formatting steps |
| 100 | About 100 formatting steps |
| 1000 | About 1000 formatting steps |
Pattern observation: The work grows directly with the number of items; double the items, double the work.
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.
[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.
Understanding how string formatting scales helps you write efficient code when working with many values, a useful skill in many programming tasks.
"What if we used a list comprehension and join() instead of adding strings inside the loop? How would the time complexity change?"