Sub topic 9
Why join beats concatenating in a loop
This chapter explains why building a string with += inside a loop is a poor habit and why str.join is the standard replacement. It assumes you know basic loops and generator expressions, that you have used str.join on a list, and that you know strings are immutable, meaning a string can never be changed after it is created.
The pattern to avoid
A common way to build a string from many pieces is to start with an empty string and append in a loop:
parts = ["alpha", "beta", "gamma"]
result = ""
for p in parts:
result += p + " "
result = result.rstrip()
print(result) # alpha beta gammaThis works and gives the right answer. Two things are wrong with it:
- It needs cleanup. Every piece gets a trailing space, so you must strip the last one afterwards.
- It does more work than it should. The cost grows faster than the input does, which this chapter explains below.
The join version is shorter and avoids both problems:
parts = ["alpha", "beta", "gamma"]
print(" ".join(parts)) # alpha beta gammajoin puts the separator only between items, so there is nothing to strip.
What `+=` really does
Strings are immutable, so result += p cannot extend the existing string in place. Conceptually, Python does this:
- Allocate a new string big enough for
resultandptogether. - Copy all characters of
resultinto it. - Copy the characters of
pafter them. - Rebind the name
resultto the new string and discard the old one.
Step 2 is the expensive part. The copy gets longer on every pass, because result keeps growing. If each piece is 10 characters and you add 1,000 pieces, the copies are about 10, 20, 30, and so on up to 10,000 characters. The total is roughly 5 million characters copied to produce a 10,000-character string.
In general, appending n pieces of similar size copies a number of characters proportional to n². Computer scientists call this quadratic time. Doubling the input roughly quadruples the work.
join avoids this. It receives all the pieces at once, adds up their lengths, allocates one result string, and copies each piece into it exactly once. The work is proportional to the total output size, which is linear time. Doubling the input roughly doubles the work.
Measuring the difference
Do not take the claim on trust. This script times both approaches at several sizes. It first checks that they produce the same text.
import timeit
def with_concat(n):
result = ""
for i in range(n):
result += str(i) + ","
return result
def with_join(n):
return "".join(str(i) + "," for i in range(n))
assert with_concat(1000) == with_join(1000)
for n in (10_000, 20_000, 40_000, 80_000):
t_concat = timeit.timeit(lambda: with_concat(n), number=3)
t_join = timeit.timeit(lambda: with_join(n), number=3)
print(f"n={n:>6} concat={t_concat:.3f}s join={t_join:.3f}s")The numbers depend on your machine and Python build, so I am not quoting any. Watch the trend as n doubles. The join column should roughly double each row. The concat column may do the same on your interpreter, and the next section explains why that does not make the pattern safe.
The CPython shortcut, and why not to rely on it
If you run the benchmark above on CPython, the standard Python interpreter, the concatenation loop may look much better than the quadratic argument predicts. CPython contains an optimization for result += piece when result is a local variable and nothing else holds a reference to that string. In that case the interpreter can try to resize the string in place instead of copying it.
Do not rely on this, for three reasons:
- It is an implementation detail. The language does not promise it. Other interpreters, such as PyPy, may not do it the same way, and CPython may change.
- It depends on conditions. If another name refers to the same string, or if the target is an attribute, a dictionary entry, or a list element rather than a plain local variable, the in-place resize cannot apply. The code then falls back to copying.
- It can fail silently. A refactor that moves the accumulator into an object attribute can turn a fast loop into a slow one, and nothing in the code tells you.
join is linear on every implementation and in every context. It also states your intent: "combine all of these pieces".
Build a list, then join once
The standard idiom is to collect the pieces in a list inside the loop and call join once afterwards:
lines = []
for n in range(1, 6):
lines.append(f"{n} squared is {n * n}")
report = "\n".join(lines)
print(report)Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25Appending to a list is cheap, because a list is mutable and grows with amortized constant cost per append. The expensive string assembly happens once, at the end.
When each piece comes from a simple expression, you can skip the explicit list and pass a generator expression:
report = "\n".join(f"{n} squared is {n * n}" for n in range(1, 6))
print(report)This behaves the same, with one detail worth knowing. str.join needs to know the total size before it allocates, so when you pass a generator it first collects all items into a list internally. A generator expression therefore does not save memory compared with a list comprehension here. Choose between them on readability.
A common mistake: joining inside the loop
Calling join repeatedly defeats the purpose:
# Slow: rebuilds the whole string on every pass
text = ""
for word in ["a", "b", "c"]:
text = " ".join([text, word]) if text else word
print(text) # a b cThis gives the right output but has the same quadratic behavior as +=, because every pass copies the full accumulated text. Collect first, join once.
Edge cases of `join`
Because join replaces so many loops, you need to know how it behaves on unusual input:
- An empty iterable gives an empty string.
",".join([])returns"". A loop that starts from""and never runs also gives"", so the two agree. - A single item gives that item with no separator.
",".join(["x"])returns"x". - Empty strings are real items.
",".join(["a", "", "b"])returns"a,,b". The empty item still gets separators around it. - Every item must be a string. A number raises
TypeError. Convert first withstr(n), as covered in the previous chapter.
print(repr(",".join([]))) # ''
print(repr(",".join(["x"]))) # 'x'
print(repr(",".join(["a", "", "b"]))) # 'a,,b'When `+` or `+=` is fine
The advice applies to loops with many iterations. Concatenation is fine, and often clearer, when you combine a small, fixed number of strings:
full_name = first + " " + lastFor mixing text with values, an f-string is usually the best choice:
full_name = f"{first} {last}"An f-string builds the result in one step. It also converts non-string values for you, which join does not.
The rule of thumb is this:
| Situation | Preferred tool |
|---|---|
| A few known pieces | f-string or `+` |
| Many pieces from a loop or iterable | `separator.join(pieces)` |
| Text mixed with values, repeated per row | f-string inside a generator, then `join` |
| Writing output incrementally to a file or stream | `write` calls, or `io.StringIO` |
io.StringIO is a good fit when you want to call write many times in different parts of a program and need the whole text at the end. It keeps an internal buffer, so you avoid recopying the text on every write:
import io
buffer = io.StringIO()
for i in range(3):
buffer.write(f"row {i}\n")
print(buffer.getvalue(), end="")Output:
row 0
row 1
row 2The same reasoning applies to bytes
Immutability makes repeated += costly for bytes as well. The matching idiom is b"".join(chunks). For data that you genuinely need to modify in place, use a bytearray, which is mutable and supports extend and += without copying the whole buffer each time. Strings have no mutable counterpart, which is why the list-then-join pattern exists.
Summary
result += piecein a loop creates a new string on every pass and copies the growing result each time, which costs time proportional to the square of the input size.- CPython sometimes hides this cost with an in-place resize, but the language does not guarantee it, and ordinary refactors can break it.
separator.join(pieces)measures the total once, allocates once, and copies each piece once.- Collect pieces in a list or generator inside the loop and call
joinonce afterwards. Never calljoininside the loop to accumulate. - Use f-strings or
+for a small, fixed number of pieces, andio.StringIOfor incremental writing.
Exercise
The function below builds a comma-separated list of squares, but it ends with a stray trailing comma and slows down badly for large n. Rewrite it with join so it returns "0,1,4,9" for n=4 and has neither problem. Also say what it returns for n=0. def squares_csv(n): result = "" for i in range(n): result += str(i * i) + "," return result
Show answer
Use a generator expression that converts each square to a string, then join once: def squares_csv(n): return ",".join(str(i * i) for i in range(n)) For n=4 it returns "0,1,4,9". The separator appears only between items, so there is no trailing comma. Each piece is copied once, so the cost is linear in the output size. For n=0 the iterable is empty, so join returns the empty string "". The original also returned "" for n=0, so the two agree on that case.
Exercise
A colleague writes text = text + word + " " inside a loop over 200,000 words and says it is fast on their machine because "Python optimizes it". Give two reasons not to depend on that.
Show answer
First, the optimization is a CPython implementation detail, not a language guarantee, so other interpreters such as PyPy may not apply it. Second, it only applies under certain conditions, for example when the accumulator is a local variable with no other references to the string. If the string is stored in an attribute or dictionary entry, or shared through another name, each pass copies the whole string again and the loop becomes quadratic. The portable fix is to append words to a list and call " ".join(words) once.