Sub topic 9
Why join beats concatenating in a loop
This chapter assumes you know for loops, += on strings, and the basics of str.join from the previous chapter. It explains why building a string with join is the better habit than appending to a string inside a loop.
Strings are immutable, so + makes a new string
A Python string cannot change after it is created. The expression result + p does not add p to the existing string. It builds a new string that holds both pieces and returns it.
Here is the loop version, next to the join version:
parts = ["alpha", "beta", "gamma"]
result = ""
for p in parts:
result += p + " "
result = result.rstrip()
print(result) # alpha beta gamma
print(" ".join(parts)) # alpha beta gammaBoth print the same text. The difference is the work done on the way.
What the loop does
On each pass, the loop creates a new string and copies all the characters collected so far into it. If the final text has n characters spread across k pieces, the early characters are copied again and again. In the worst case the total copying grows with the square of the data size. Doubling the input can roughly quadruple the time.
What join does
join receives all the pieces at once. It works out the total length, allocates the result one time, and copies each piece into place once. The work grows in step with the data size. It also needs no cleanup, because the separator goes only between items. The loop above had to call rstrip() to remove the trailing space it added after the last item.
Measuring the difference
You can check this yourself with the timeit module. The two functions below build the same text, and the assert confirms that.
import timeit
parts = ["word"] * 100_000
def with_loop():
result = ""
for p in parts:
result += p + " "
return result.rstrip()
def with_join():
return " ".join(parts)
assert with_loop() == with_join()
print("loop:", timeit.timeit(with_loop, number=5))
print("join:", timeit.timeit(with_join, number=5))The exact numbers depend on your machine and Python version. On most setups join is clearly faster, and the gap widens as you raise the list size.
A caveat about CPython
The standard Python implementation, CPython, has an optimization for result += p. When nothing else refers to result, it can sometimes extend the string in place instead of copying it. That is why a small loop may look fast in a test.
Do not rely on this. The language does not guarantee it, other implementations such as PyPy may not do it, and it stops working when another variable holds a reference to the same string. join has predictable cost everywhere.
When concatenation is fine
For a few pieces, + or an f-string is clearer and the cost does not matter:
name = "Ada"
greeting = "Hello, " + name + "!"
greeting_f = f"Hello, {name}!"
print(greeting == greeting_f) # TrueUse join when the number of pieces is not known in advance, or when it can grow large, such as lines read from a file or rows of a report.
Building the list first
A common pattern is to collect pieces in a list and join once at the end. Appending to a list is cheap because lists are mutable and grow in place.
lines = []
for i in range(1, 4):
lines.append(f"row {i}")
report = "\n".join(lines)
print(report)If the items are not strings, convert them first, as shown in the previous chapter, for example with ",".join(str(n) for n in numbers).
Exercise
This function builds a comma-separated line from a list of integers using a loop. Rewrite it with join so that it returns the same result and has no trailing comma. def to_line(numbers): out = "" for n in numbers: out += str(n) + "," return out[:-1]
Show answer
Convert each number to a string and join once: def to_line(numbers): return ",".join(str(n) for n in numbers) For [1, 2, 3] both versions return "1,2,3". The join version avoids creating a new string on every pass, needs no slicing to remove the last comma, and also works for an empty list, where the loop version's out[:-1] happens to return "" but only by luck of slicing an empty string.