Use "".join(iterable) (with a separator like "".join(parts) or "\n".join(lines)) to concatenate a collection or loop of strings in $O(n)$ time, and use f-strings (f"{a}{b}") when combining a small, fixed number of variables in a single expression. Avoid repeated += concatenation inside loops for large datasets, as Python strings are immutable and repeated += can degrade to $O(n^2)$ memory copying when references are shared.
Basic Example
# 1. Fastest for loops / large sequences: collect in a list and call "".join() once
words = ["Python", "is", "fast", "and", "clean"]
sentence = " ".join(words)
print(sentence) # Output: "Python is fast and clean"
# 2. Fastest for building strings dynamically in a loop
parts = []
for i in range(1, 5):
parts.append(f"item_{i}")
result = ", ".join(parts)
print(result) # Output: "item_1, item_2, item_3, item_4"
# 3. Fastest for a small, fixed number of variables: f-strings
first, last = "Ada", "Lovelace"
full_name = f"{first} {last}"
print(full_name) # Output: "Ada Lovelace"
Key Details & Performance Mechanics
- Why
"".join()is $O(n)$ linear time:str.join()makes two fast passes over the input sequence: first it calculates the exact total byte length of all strings combined, allocates a single output buffer once, and then copies each piece directly into place—eliminating intermediate string allocations. - Pass a list comprehension rather than a generator expression to
"".join(): Becausestr.join()needs to inspect the sequence twice (once to compute total length, once to copy), passing a generator expression like"".join(str(x) for x in items)forces Python to materialize an internal list anyway, which is slightly slower than passing a list comprehension"".join([str(x) for x in items]). - Why
+=in a loop is risky (CPython optimization caveat): Because Pythonstrobjects are immutable,s += chunknormally allocates a new string and copies both operands on every iteration ($O(n^2)$). While CPython includes a reference-counting optimization that resizes unshared strings in place whensys.getrefcount(s) == 2, that optimization silently breaks as soon as another variable, function call, or debugger holds a reference tos—and does not exist in PyPy or other Python runtimes. Relying onlist.append()+"".join()guarantees $O(n)$ performance everywhere. - Using
io.StringIOfor file-like streaming buffers: When incrementally building huge text payloads across multiple helper functions that expect a file-like.write()interface, write chunks to anio.StringIO()buffer and callbuffer.getvalue()once at the end.
Comparison of String Concatenation Methods
| Method | Syntax | Time Complexity | Memory Allocations | Best Used When |
|---|---|---|---|---|
"".join(list) |
"".join(parts) |
$O(n)$ | 1 final allocation | Combining lists, iterables, or accumulating chunks in a loop. |
| f-strings | f"{a}-{b}-{c}" |
$O(n)$ | 1 final allocation | Formatting and joining a small, known number of variables inline. |
io.StringIO |
buf.write(s); buf.getvalue() |
$O(n)$ | Amortized buffer growth | Streaming text across functions expecting a file-like .write() API. |
+ / += operator |
s += chunk |
$O(n^2)$ worst-case | Up to $O(n)$ copies | Joining 2–3 strings once outside a loop (avoid inside loops). |
You must log in or register to comment.
