String formatting using f-strings in Python - Time & Space 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.
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 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).
As the number of names grows, the number of formatted greetings grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 string formats |
| 100 | About 100 string formats |
| 1000 | About 1000 string formats |
Pattern observation: The work grows directly with the number of names.
Time Complexity: O(n)
This means the time to format strings grows in a straight line as you add more names.
[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.
Understanding how string formatting scales helps you write efficient code when working with many pieces of text.
"What if we used a single f-string to format all names at once? How would the time complexity change?"