When did Python's += string concatenation suddenly become smart?

Revision en1, by Shisuko, 2021-08-30 04:23:40

For almost a decade now, I've been told to avoid using += on strings in Java and Python. Because they are immutable, the += creates an entirely new string and has to copy over all the characters from the left-hand side. Thus, putting a += in a loop could have your program's complexity degrade into quadratic in some cases if you're not careful.

But then just last week, I learned that CPython actually hands string concatenation smartly! On the Custom Test tab here on Codeforces, the following code runs in just 280ms when submitted to Python 3.8.10.

s = ''
for _ in range(10**6):
    s += 'a'
print(len(s))

(In contrast, it badly TLEs when submitting to PyPy 3.7, so I suppose that's one thing Python has over PyPy, but it's not like join was too hard to do, though, anyway).

Was this a recent change? How long have I been living a lie?

Tags #python 3, #string

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English Shisuko 2021-08-30 04:23:40 944 Initial revision (published)