Why is "".join(list_of_strings) preferred over += inside a loop?
Strings are immutable, so each += may copy the whole string built so far, which can become quadratic. join() computes the total size once and copies each piece a single time, so it runs in linear time.
Explain it simply
Imagine pasting 1,000 small notes onto one chart paper. With +=, you rewrite the entire chart paper every time a note is added. With join, you first measure how much paper you need, then stick every note on exactly once.
CPython sometimes optimises s += x when nothing else references s, but this is an implementation detail and not guaranteed, so you should not depend on it.
Example
words = ["Jai", "Hind", "from", "Jamshedpur"]
sentence = " ".join(words)
print(sentence) # Output: Jai Hind from Jamshedpur
result = ""
for w in words:
result += w + " "
print(result.strip()) # Output: Jai Hind from Jamshedpur
print(",".join(str(n) for n in range(5))) # Output: 0,1,2,3,4join is called on the separator, and it only accepts strings, which is why the last line converts numbers first.
What to say in the interview
"Because strings are immutable, repeated += creates new string objects and can cost O(n squared) overall. str.join builds the result in one pass, O(n). I collect pieces in a list and join at the end."
Common mistakes
- Calling
joinon the list (words.join(" ")). It is a string method. - Passing integers to join without converting them to str.