0
0
Pythonprogramming~5 mins

String formatting using f-strings in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: String formatting using f-strings
O(n)
Understanding Time Complexity

Let's see how the time it takes to format strings with f-strings changes as we add more data.

We want to know how the work grows when formatting many strings.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

names = [f"Name{i}" for i in range(n)]
results = []
for name in names:
    greeting = f"Hello, {name}!"
    results.append(greeting)

This code creates greetings for a list of names using f-strings.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping over each name and creating a formatted string.
  • How many times: Once for each name in the list (n times).
How Execution Grows With Input

As the number of names grows, the number of formatted greetings grows the same way.

Input Size (n)Approx. Operations
10About 10 string formats
100About 100 string formats
1000About 1000 string formats

Pattern observation: The work grows directly with the number of names.

Final Time Complexity

Time Complexity: O(n)

This means the time to format strings grows in a straight line as you add more names.

Common Mistake

[X] Wrong: "Formatting one string takes the same time no matter how many strings I format."

[OK] Correct: Each string needs its own formatting step, so more strings mean more work overall.

Interview Connect

Understanding how string formatting scales helps you write efficient code when working with many pieces of text.

Self-Check

"What if we used a single f-string to format all names at once? How would the time complexity change?"